1

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?

2 Answers 2

2

The solution using call_user_func_array function:

...
$result = call_user_func_array("array_merge", [$result, $array1, $array2]);
...
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.