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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With