Tricky
Tricky

Reputation: 43

Unset a value in a multi-dimensional array based on one of the values

I am attempting to unset a row in a multi-dimensional array based on finding one of the values (the product code)

Here is a slightly simplified structure/content of the array:

Array ([0] => Array ( [item_id] => code1 [item_desc] => first product  [item_price] => 5.45 )
[1] => Array ( [item_id] => code2 [item_desc] => second product  [item_price] => 9.25 ))

The following works fine except when trying to delelete the first item [0] in the array - so the first item in the basket cannot be deleted.

$pid = 'code2';

$key = array_search($pid, array_column($_SESSION['cart_array'], 'item_id'));

if($key) {
    unset($_SESSION['cart_array'][$key]);
    sort($_SESSION["cart_array"]);
    }

Where the value of $pid = 'code1', $key returns false and the session variable content remains unchanged

I have tried using a foreach loop, which will find the value but I seem unable to get back to the key

foreach ($_SESSION['cart_array'] as $search)
    {
        if($pid == $search['item_id'])
        {
        echo key($search);            // returns item_id
        }
    }

Any help much appreciated.

Upvotes: 0

Views: 46

Answers (3)

deceze
deceze

Reputation: 522032

Use a simpler approach:

$_SESSION['cart_array'] = array_filter($_SESSION['cart_array'], function ($item) use ($pid) {
    return $item['item_id'] != $pid;
});

This filters all items out of the array which match $pid.

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

When using the return value of array_search(), this may return 0 for the first item (as you know) and when you test 0 - this is the same as false, you need to check the key to be not equivalent to false...

if($key !== false) {

Upvotes: 1

jameslafferty
jameslafferty

Reputation: 2182

I think this is what you want.

foreach ($_SESSION['cart_array'] as $key => $search)
{
    if($pid == $search['item_id'])
    {
        echo $key;
    }
}

Upvotes: 0

Related Questions