Array_shift from attribute in array

Im trying to remove the first element of the last array

Array:

$harbours = array( '67' => array('boat1', 'boat2'), '43' => array('boat3', 'boat4') ); 

I want to remove and return boat3

 $last = end($harbours); $boat = array_shift($last); 

If I then print_r ($harbours) , "boat3" still exists.

+4
source share
3 answers

This is because in array_shift you are changing a copy of the final array.

You need to get a reference to the destination array in order to move it.

Try the following:

 end($array); $currKey = key($array); //get the last key array_shift($array[$currKey]); 

See demo: http://codepad.org/ey3IVfIL

+10
source
 $last = end($harbours);<br /> //First reverse the array and then pop the last element, which will be the first of original array.<br /> array_pop(array_reverse($last)); 
-1
source

This code should work as expected:

 $harbours = array('67' => array('boat1', 'boat2'), '43' => array('boat3', 'boat4')); end($harbours); $key = key($harbours); $x = $harbours[$key]; array_shift($x); $harbours[$key] = $x; print_r($harbours); 
-2
source

All Articles