• PHP Help
  • I don't understand how array_pop is supposed to work on a SESSION array

I don't understand how array_pop is supposed to work on a SESSION array

I want to use array_pop to remove the last item added to the SESSION array. So it would remove the REQUEST item. The problem is that nothing is left in the session array because I pop off the last item each time that the form is submitted. Maybe I need to use array_push to push the popped items back on to the SESSION array after the logic has been applied. I don't understand how array_pop is supposed to work on a SESSION array. Can anyone explain to me what behaviour to expect? I expected to get a SESSION array with the REQUEST item removed but I thought that I would still have all of my SESSION items.

    array_pop would have the same effect on the session array that it has on any other array: it will remove the last item (whichever item that happens to be). If you remove an item from the session array it gets removed from the session (since the array is how you access the session). Once it's gone the second-to-last element is now the last so when you call array_pop again, that element will be removed.

    You have two choices:

    1. Remove the element you want to remove by name explicitly (unset($_SESSION['REQUEST']) if that is how the element is named). This will remove it from the session, but won't remove anything else.
    2. If you don't want to remove it from the session but just from the array on this particular occasion, copy the session array to a temporary one and use the temporary array.

    It sounds like the first is more what you're after. It has the advantage of not just assuming that the element you want to remove is the last one.

    Write a Reply...