简体   繁体   中英

Session array is not unsetting when remove cart item is done in php

I written this code for unsetting the session array when remove cart item button is clicked:

$i=0;
    foreach ($_SESSION["items"] as $cart_itm) //loop through session array var
    {           
    //echo count($_SESSION['items']);
        if($cart_itm["id"] == $item_Id){ //item id is equal
            if(count($_SESSION['items']) == 1)
            {
            //echo "count1";
                unset($_SESSION['items']);
                $empty = 'Y';
            }
            else
            {

            echo $i."--";
            echo $cart_itm["id"];
            echo "------";
                unset($_SESSION['items'][$i]);
                $empty = 'N';

            }
        }
        $i++;
     }

But it unsets the first row in Shopping cart table when remove cart item is clicked for first.But when remove cart item is clicked for second row, the array is not unset and item is not removed from cart. Also, if I click the remove cart item for 3rd row, the second row is deleted instead of 3rd row.

Please let me know why this is happening.

How it make a sense just to use foreach for unset $_SESSION["items"],

What's the problem , if you will do like this:

 if(isset($_SESSION["items"]) && count($_SESSION["items"])>0)
 unset($_SESSION["items"]);

Thanks

Try this approach

for($i=0; $i < count($_SESSION["items"]); $i++)
{           
    if($_SESSION["items"][$i] == $item_Id){
        unset($_SESSION['items'][$i]);
        break;
    }
}

let me know if I missed something.

This problem is may be due to incorrect key is passed by your loop to unset desired session value. Instead of using $i++ approach , you can simply use KEY => VALUE PAIR.

Example:

foreach ($_SESSION["items"] as $sessionKey=>$cart_itm) //loop through session array var
{           
    //echo count($_SESSION['items']);
    if($cart_itm["id"] == $item_Id){ //item id is equal
        if(count($_SESSION['items']) == 1)
        {
            //echo "count1";
            unset($_SESSION['items']);
            $empty = 'Y';
        }
        else
        {

            echo $sessionKey."--";
            echo $cart_itm["id"];
            echo "------";
            unset($_SESSION['items'][$sessionKey]);
            $empty = 'N';

        }
    }        
 }

Try this approach , it may be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM