9

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?

1
  • 2
    I don't see why it shouldn't be working. Show your code. Commented Mar 13, 2013 at 23:51

1 Answer 1

19

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was indeed assigning the return value to a new variable

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.