0

I am really stuck with this. It is an array within an array such as:

Array ( [0] => Array ( [item] => product1 [unitprice] => 15 [quantity] => 1 ) [1] => Array ( [item] => product2 [unitprice] => 15 [quantity] => 1 ) )

I have tried to remove a specific item using:

$pid=$_GET['id']; (where id = product1)

$delete=array_splice($_SESSION['cart'], array_search($id, $_SESSION['cart']), 1);
unset($delete);    

print_r($_SESSION['cart']);

This seems to randomly remove items. Any help would be greatly appreciated

Tony Stark
  • 8,064
  • 8
  • 44
  • 63

2 Answers2

2
<?php 
function searchForItem($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['item'] === $id) {
           return $key;
       }
   }
   return null;
}

$pid=$_GET['id'];

$id = searchForItem($pid, $_SESSION['cart']);

unset($_SESSION['cart'][$id]);

?>
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

you mean:

foreach($_SESSION['cart'] as $index => $v) { 
    if(($key = array_search($pid, $v)) !== false) {
        unset($_SESSION['cart'][$index]);
    }
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162