Jump to content

Issues with unsetting SESSION arraykey


7blake

Recommended Posts

HI, I'm having trouble with unsetting a key from SESSION. I can unset the cart, but when I try to target the key, it doesn't work.
    Are there some regular things I should be looking for? The only thing I can think of is that I'm re-initializing the key by accident elsewhere in my code.

if(isset($_POST['mainCartDelete'])){
    
    unset($_SESSION['cart_array'][21]); 
       
    $sessionArray = $_SESSION['cart_array'];     
  
    print_r ($sessionArray);
   
}

Print_r returns

Array ( [0] => Array ( [item_id] => 21 [quantity] => 1 ) ) 
Link to comment
https://forums.phpfreaks.com/topic/293010-issues-with-unsetting-session-arraykey/
Share on other sites

$_SESSION['cart_array'] contains an array of items. Each item has their own sub array. The sub array contains the item_id a value

 

$_SESSION['cart_array'][21] will return the item in the cart_array that has the numerical key of 21. This will not return the sub array with the item_id value of 21

 

To get rid of the item with the item_id of 21 you need to use numerical index 0.

unset($_SESSION['cart_array'][0]);

 

You should restructure your $_SESSION['cart_array'] so your item ids are used as the keys for each item in the array and used as a value in the sub array

Oh man.. thankyou very much for explaining that. I was just on the tail of figuring that out. Very much appriciated for the information and time.

if(isset($_POST['mainCartDelete'])){
	
$cartArray = $_SESSION['cart_array'];
$test = "";
foreach($cartArray as $key => $item) {
    
    $test .= $key . " ";
    if($key == 21){
    unset($_SESSION['cart_array'][$key]);
    }
}
	echo $test;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.