1

Hey guys I have this array :

Array
(
    [qty] => 1
    [id] => 2
    [name] => sallate me gjera plot 
    [price] => 8
    [category_id] => 25
    [dish_name] => sallate me gjera plot 
    [dish_id] => 2
    [dish_category_id] => 25
    [dish_qty] => 1
    [dish_price] => 8
)
Array
(
    [qty] => 1
    [id] => 1
    [name] => sallate cezar
    [price] => 12
    [category_id] => 25
    [dish_name] => sallate cezar
    [dish_id] => 1
    [dish_category_id] => 25
    [dish_qty] => 1
    [dish_price] => 12
)

And what I'm trying to do is to unset the item by dish_id. This is the way I intend to do that :

if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
        { 
            foreach ($_SESSION["cart_products"] as $key =>$cart_itm)
            {   
                if($cart_itm["dish_id"]==$removable_id)
                {
                    unset($cart_itm[$key]);
                }
            }
        }

Can anyone tell me what I'm doing worng..thanks :D

4
  • 1
    change unset($cart_itm[$key]); to unset($_SESSION["cart_products"][$key]) and check Commented Mar 25, 2016 at 10:30
  • That was it thanks alot :D Commented Mar 25, 2016 at 10:34
  • sorry @Anant first day here..I'm getting used to this :/ Commented Mar 25, 2016 at 15:06
  • Sorry for my wordings if it hurts you. Commented Mar 25, 2016 at 15:44

2 Answers 2

1

Actually you need to unset data from actual array which is $_SESSION["cart_products"] not $cart_itm.

So change unset($cart_itm[$key]); to unset($_SESSION["cart_products"][$key])

Sign up to request clarification or add additional context in comments.

Comments

1

As alternative, you can use array_filter() with an anonimous function:

$removable_id = 1;

$_SESSION["cart_products"] = array_filter
( 
    $_SESSION["cart_products"], 
    function( $row ) use( $removable_id )
    {
        return $row['dish_id'] != $removable_id; 
    }
);

print_r( $_SESSION["cart_products"] );

will print:

Array
(
    [0] => Array
        (
            [qty] => 1
            [id] => 2
            [name] => sallate me gjera plot 
            [price] => 8
            [category_id] => 25
            [dish_name] => sallate me gjera plot 
            [dish_id] => 2
            [dish_category_id] => 25
            [dish_qty] => 1
            [dish_price] => 8
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.