TeaNyan
TeaNyan

Reputation: 5079

Append elements of an array to another array

I have some unknown number of iterations in which every iteration gives two arrays.

for ($i = 0; $i<sizeof($foo); $i++) {
    $array1 = //do something
    $array2 = //do something
    $result = //($result + $array1 + $array2)
}

What I want to do is to append the elements of those arrays to $result.

If I use array_merge() I cannot add the previous elements of $result to it.

If I use array_push() I will get a 2D array which I don't want.

array_push($result, $array1, $array2);

So what is the best solution to my problem? Is there any way to do it without iterating through each array and pushing every element?

Upvotes: 1

Views: 207

Answers (2)

mickmackusa
mickmackusa

Reputation: 47874

Assuming you have numeric keys, to push a variable number of elements into the result array without creating unwanted depth, use the spread operator with array_push() -- it performs better than merging the result array with the other arrays and saving the merged data back into the result array.

Code: (Demo)

array_push($result, ...$array1, ...$array2);

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using call_user_func_array function:

...
$result = call_user_func_array("array_merge", [$result, $array1, $array2]);
...

Upvotes: 2

Related Questions