Search code examples
phparraysmultidimensional-arrayunset

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.


Solution

  • I think this is what you want.

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