Jarrow
Jarrow

Reputation: 81

How can I delete a subArray, if search values matches?

I am fairly new to working with arrays and I am stuck on being able to delete an entry.

If I have:

$del_itemid = 58;
$del_modiifier = 1;

How do I search through my array $orders and unset the array containing these variables ?

$orders =  Array
(
    [0] => Array
        (
            [itemid] => 67
            [modifier] => 1
            [quantity] => 1
            [unit_price] => 17.00
            [categoryid] => 2
        )

    [1] => Array
        (
            [itemid] => 58
            [modifier] => 1
            [quantity] => 1
            [unit_price] => 18.00
            [categoryid] => 5
        )

    [2] => Array
        (
            [itemid] => 72
            [modifier] => 1
            [quantity] => 1
            [unit_price] => 10.00
            [categoryid] => 3
        )

)

EDIT:

This is what I have been trying:

$i = 0;

foreach($orders as $key => $value) {

    $itemid = $value['itemid'];
    $modifier = $value['modifier'];

    if ($itemid == $del_itemid && $modifier == $del_modifier)  {
        unset($_SESSION['cart'][$i]);
        break;                  
    }

    $i++;

}

Upvotes: 1

Views: 62

Answers (2)

Jarrow
Jarrow

Reputation: 81

I found a solution based on what I was originally trying to achieve with the loop. If I use array_splice() instead of unset() it will reset the index so that it remains possible to loop through the array without there being holes in the index:

$i = 0;

foreach($orders as $key => $value) {

    $itemid = $value['itemid'];
    $modifier = $value['modifier'];

    if ($itemid == $del_itemid && $modifier == $del_modifier)   {
        array_splice($orders, $i,1);       
    }    

    $i++;  

}

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

Since you want to check 2 values, I would use array_filter() to loop through the array and filter all subArrays out, where both values are equal to your search values, e.g.

$newArray = array_filter($orders, function($v)use($del_itemid, $del_modiifier){
    if($v["itemid"] == $del_itemid && $v["modifier"] == $del_modiifier)
        return FALSE;
    return TRUE;
});

Upvotes: 2

Related Questions