Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_shift() not working for me. What am I doing wrong?

Tags:

php

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.

like image 801
user77413 Avatar asked Jun 30 '11 22:06

user77413


People also ask

How to add new value in existing array in PHP?

The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

What is array_ shift in PHP?

The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).


1 Answers

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);
like image 127
Felix Kling Avatar answered Oct 25 '22 06:10

Felix Kling