3

I have a two dimensional array and wish to always delete/unset the last array item (in this case Array[3]) in the code sample below, before I put it into a SESSION.
I am still a novice with php and have tried the following with no success.
Any help would be greatly appreciated.

if (is_array$shoppingCartContents)) {  
   foreach($shoppingCartContents as $k=>$v) {
      if($v[1] === 999999) {
         unset($shoppingCartContents[$k]);
      }
   }
}


$shoppingCartContents = Array
(
[0] => Array
    (
        [productId] => 27
        [productTitle] => Saffron, Dill & Mustard Mayonnaise 
        [price] => 6.50
        [quantity] => 3
    )

[1] => Array
    (
        [productId] => 28
        [productTitle] => Wasabi Mayonnaise 
        [price] => 6.50
        [quantity] => 3
    )

[2] => Array
    (
        [productId] => 29
        [productTitle] => Chilli Mayo
        [price] => 6.50
        [quantity] => 2
    )

[3] => Array
    (
        [productId] => 999999
        [productTitle] => Postage
        [price] => 8.50
        [quantity] => 1
    )
)
1
  • There is a possible typo in your code: is_array$shoppingCartContents) Commented Jan 10, 2013 at 1:30

2 Answers 2

3

Just use array_pop()

$last_array_element = array_pop($shoppingCartContents);
// $shoppingCartContents now has last item removed

So in your code:

if (is_array($shoppingCartContents)) {  
    array_pop($shoppingCartContents); // you don't care about last items, so no need to keep it's value in memory
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your code will fail as you're using strings for keys, not numbers, so the comparison

if($v[1] === 999999)

will never match, and should be checking $v['productId'].

For your use case, rather than looping through the array, you can just pop the last item off:

array_pop($shoppingCartContents);

array_pop removes the last item from an array. It returns that last item, but since you don't want to keep the last item, we're not saving the return value.

Alternatively, if you still wanted to use unset, you could get the last key, and then unset using that.

Finally, as it looks like you've got a true list (i.e. consecutive, numerical indices), you could get away with something like unset($shoppingCartContents[count($shoppingCartContents)-1]);

All that being said, array_pop is the way to go.

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.