Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_unshift for multidimensional arrays

I am trying to insert an array into a multidimensional array as the first element. Example of my original array

Array (
    0 => array ( "point1.0" => "some data", "point2.0" => "some data" )
    1 => array ( "point1.1" => "some data", "point2.1" => "some data" )
)

Then I have the array that I want to insert as the first Element

$newArray = array("point1.2" => "some data", "point2.2" => "some data" )

And my result should be

Array (
    0 => array ( "point1.2" => "some data", "point2.2" => "some data" )
    1 => array ( "point1.0" => "some data", "point2.0" => "some data" )
    2 => array ( "point1.1" => "some data", "point2.1" => "some data" )
)

array_unshift seems to fail in this case. Are there any better solutions than creating a new array and inserting every subarray through a foreach loop?

like image 626
Marco Avatar asked Mar 13 '13 23:03

Marco


1 Answers

array_unshift should work for you. It should be noted that the function modifies the array passed to it and does not return a new array, so you should not be assigning the return value back to the array variable.

Correct:

array_unshift($arr, $newArray);

Incorrect:

$arr = array_unshift($arr, $newArray);
like image 179
Tim Cooper Avatar answered Oct 23 '22 10:10

Tim Cooper