7blake Posted December 10, 2014 Share Posted December 10, 2014 (edited) 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 December 10, 2014 by 7blake Quote Link to comment https://forums.phpfreaks.com/topic/293010-issues-with-unsetting-session-arraykey/ Share on other sites More sharing options...
Solution Ch0cu3r Posted December 10, 2014 Solution Share Posted December 10, 2014 (edited) $_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 December 10, 2014 by Ch0cu3r 1 Quote Link to comment https://forums.phpfreaks.com/topic/293010-issues-with-unsetting-session-arraykey/#findComment-1499206 Share on other sites More sharing options...
7blake Posted December 10, 2014 Author Share Posted December 10, 2014 (edited) 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 December 10, 2014 by 7blake Quote Link to comment https://forums.phpfreaks.com/topic/293010-issues-with-unsetting-session-arraykey/#findComment-1499207 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.