Reputation: 55
I am having a problem deleting/unsetting session variables.
For example if I have 3 items in a shopping cart 1,2,3 and I deleted all those items. They should be deleted from the session but instead they're hidden.
Unset both variables
This is where I unset the 2 session variables cart_array
and minicart
<?php
if (isset($_POST['index_to_remove']) && (!empty($_SESSION["cart_array"]["minicart"]))) {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]["minicart"]) <= 1) {
unset($_SESSION["cart_array"]["minicart"]);
} else {
unset($_SESSION["cart_array"]["minicart"]["$key_to_remove"]);
sort($_SESSION["cart_array"]["minicart"]);
}
}
?>
HTML
echo '<form action="cart.php" method="post">
<input name="deleteBtn' . $item_id . '"
type="submit" value="Delete" />
<input name="index_to_remove"
type="hidden" value="' . $i . '" />
</form>';
also in this header.php page I echo out the both session varibles cart_array
and minicart
MY QUESTION IS/ ISSUES IS
if you look in unset variables it is meant to unset both session variables cary_array
and minicart
based on the itemid which is assigned to those sessions.
Now if I click on the delete button this deletes the item from cart BUT *WHY ISN'T IT DELETING the session variable cary_array
and minicart
from the session?
I know it has been deleted because the code below shows that instead of the session variable getting deleted(unset) is not
if(isset($_SESSION ['cart_array']) && !empty($_SESSION['cart_array'])) {
echo ("I am still here");
}
Upvotes: 1
Views: 337
Reputation: 3623
When you do:
unset($_SESSION['cart_array']['minicart']);
you are just unsetting "minicart", not "cart_array".
If you want to unset both "cart_array" and "minicart", you should just do:
unset($_SESSION['cart_array']);
or
$_SESSION['cart_array'] = array();
To test if the arrays are empty or not, just:
if ($_SESSION['cart_array']):
else:
endif;
Upvotes: 2
Reputation: 10054
Try this:
$_SESSION['cart_array'] = Array();//This should empty the cart.
Then test only for empty. The reason is most likely due to the way PHP's GC works. Read this answer for better explanation.
Upvotes: 2