Home > Software engineering >  How to insert an array at the beginning of another array in PHP?
How to insert an array at the beginning of another array in PHP?

Time:02-16

I have two different array.

$array_1 = array('a','b','c');
$array_2 = array('d','e','f');

I want to insert $array_2 at the beginning of $array_1! But can't figure it out, how to do it!

I have tried array_unshift()

It's generating array, which is look like this,

array_unshift($array_1, $array_2);
print_r($array_1);
Array
(
    [0] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )

    [1] => a
    [2] => b
    [3] => c
)

But when I am using array_unshift() like this

array_unshift($array_1, 'd','e','f');

Then it's working as expected. And the result is,

Array
(
    [0] => d
    [1] => e
    [2] => f
    [3] => a
    [4] => b
    [5] => c
)

Now, the question is, How to insert an array at the beginning of another array like the result of array_unshift($array_1, 'd','e','f')?

CodePudding user response:

You can merge two or more array with array_merge()

$array_1 = array('a','b','c');
$array_2 = array('d','e','f');

$a3 =array_merge( $array_2, $array_1 );
print_r($a3);

Output:

Array
(
    [0] => d
    [1] => e
    [2] => f
    [3] => a
    [4] => b
    [5] => c
)

array_merge()

CodePudding user response:

You can use array_merge

array_merge($array_1,$array_2)
  • Related