0

I've created the multidimensional array in the following format

Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )

When I try to unset an particular array element based on id, after unset i'm getting the array like below.

Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )

The array element is getting unset, but the next array element doesn't move to the deleted array position.

For unset an array element, I'm using the following code.

$i = 0;
foreach($cartdetails["products"] as $key => $item){
    if ($item['id'] == $id) {
        $match = true;
        break;
    }
    $i++;
}
if($match == 'true'){
    unset($cartdetails['products'][$i]);
}

How to solve this issue? Please kindly help me to solve it.

Thanks in advance.

  • Arrays have fixed positions. You'll need to move them manually in case you want to. – Menno Jun 19 '13 at 08:49
  • 1
    Please check this link http://stackoverflow.com/questions/5217721/how-to-remove-array-element-and-then-re-index-array – ejo Jun 19 '13 at 08:53

4 Answers4

1

Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.

$i = 0;
foreach($cartdetails["products"] as $key => $item){
    if ($item['id'] == $id) {
        $match = true;
        break;
    }
    $i++;
}
if($match == 'true'){
    unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
  • Thank you for your reply. I've tried what you've mentioned above. But its not working.. –  Jun 19 '13 at 08:56
  • Its Working fine.. After assigning like `$cartdetails['products'] = array_values($cartdetails['products']);` –  Jun 19 '13 at 09:04
0

Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.

http://www.php.net/manual/en/function.array-splice.php

http://php.net/manual/en/function.unset.php

Mir
  • 1,575
  • 1
  • 18
  • 31
0

Why don't you use this???

$id = 9;
foreach($cartdetails["products"] as $key => $item){
   if ($item['id'] == $id) {
       unset($cartdetails['products'][$key]);
       break;
   }    
 }
Samoth
  • 1,691
  • 17
  • 24
0

Why do you use $i++ to find an element to unset?

You can unset your element inside foreach loop:

foreach($cartdetails['products'] as $key => $item){
    if ($item['id'] == $id) {
        unset($cartdetails['products'][$key]);
        break;
    }
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Sergei Beregov
  • 738
  • 7
  • 19