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
    )
)
Uttara
  • 2,496
  • 3
  • 24
  • 35
Twobears
  • 109
  • 9

2 Answers2

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
}
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
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.

Community
  • 1
  • 1
ernie
  • 6,356
  • 23
  • 28