5

I am creating an array and want to delete the first element of the array and re-index it. From what I can tell, array_shift() is the right solution. However, it is not working in my implementation.

I have a member variable of my class that is defined as an array called $waypoint_city. Here is the variable output prior to shifting the array:

print_r($this->waypoint_city);

Result:

Array ( [0] => [1] => JACKSONVILLE [2] => ORLANDO [3] => MONTGOMERY [4] => MEMPHIS )

If I do the following, I get the correct result:

print_r(array_shift($this->waypoint_city));

Result:

Array ( [0] => JACKSONVILLE [1] => ORLANDO [2] => MONTGOMERY [3] => MEMPHIS )

However, if I try to reassign the result to the member variable it doesn't work... Anyone know why that is?

$this->waypoint_city = array_shift($this->waypoint_city);

If I try to print_r($this->waypoint_city) it looks like nothing is in there. Thanks to anyone who can save the hair that I haven't pulled out, yet.

3 Answers 3

11

array_shift[docs] changes the array in-place. It returns the first element (which is empty in your case):

Returns the shifted value, or NULL if array is empty or is not an array.

All you have to do is:

array_shift($this->waypoint_city);
Sign up to request clarification or add additional context in comments.

1 Comment

This is a classic case of RTFM... I feel like an idiot. Thanks for setting me straight. Thanks!!!
2

That's because there IS nothing there. You have element 0 set to nothing, and array_shift returns the shifted element, which the first time through is null.

Comments

1

array_shift() gets its parameter as reference, so you should call array_shift() like this:

$shiftedElement = array_shift(&$this->waypoint_city);

Comments

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.