lacyeex lacyeex - 3 months ago 6
PHP Question

How can I combine two arrays without creating an extra array level?

I am combining 2 arrays into a new array using this code:

$newarray = array($array1, $array2);


The output is like this:

Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => Array
(
[0] => 4
[1] => 7
)

[1] => Array
(
[0] => 20
[1] => 10
)
)
)


But I want to change the structure, so the array will be like this:

Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 4
[1] => 7
)
[2] => Array
(
[0] => 20
[1] => 10
)
)


Is there any way to change the structure?

Answer

You could use array_merge instead of array.

$new_array = array_merge([$array1], $array2);

Note that in order for this to work, $array1 needs to be wrapped in another array: [$array1]. Otherwise $array1 will end up as the parent of $array2 instead of its sibling, and you'll get

[3, 1, [4, 7], [20,10]]

instead.