Jump to content

Issues with unsetting SESSION arraykey


Go to solution Solved by Ch0cu3r,

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 ) ) 
Edited by 7blake
Link to comment
https://forums.phpfreaks.com/topic/293010-issues-with-unsetting-session-arraykey/
Share on other sites

  • Solution

$_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

Edited by Ch0cu3r
  • Like 1

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;
}
Edited by 7blake
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.