4

Im trying to remove the first element of the last array

The 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' is still there.

0

3 Answers 3

10

That is because in array_shift you are changing a copy of the end array.

You need to get a reference of the end array in order to shift it.

Try this:

end($array);

$currKey = key($array); //get the last key

array_shift($array[$currKey]);

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for responding. yeah, i realise that, but i tried end(&$harbours) and that didnt work either
indeed. Most 90% of the things PHP do are by copying (not reference). So to modify the last element you need to point to it, or use the original array's reference (e.g. array_shift($harbour[sizeof($harbour)-1])
@Christian I just added a demo ^_^
@BradChristie sizeof will not work here since the arrays are not zero indexed.
@Christian No problem ^_^ happy to help!
|
-1
$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));

3 Comments

it would be great if you can add a comment to mention the reason to down-vote an answer...
although I'm not the one who downvoted, your answer is basically the same code that Asker has array_pop(array_reverse($last)) is the same as array_shift($last) - have you even tested your code before posting it?
@Slayer Birden, I agree with what you are saying. You are absolutely correct. I have noticed this very minute but important fact about some core functions because of your comment.
-2

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 Comments

wow, you made this waaaayyy more complicated than it has to be.
@Neal: so, vote down for it? That's my way and I see that you do it elegantly.

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.