1

Hi I am trying to remove an array element using a foreach loop, but it does nothing. I need the index to be completely gone rather than making it null. Here is what I have tried:

foreach ($_SESSION['cart']  as &$arrays3) {
    if($arrays3['id'] == $id){
        unset($arrays3);
    }
}

Note, the array value for each key contains an associative array.

jfly
  • 7,715
  • 3
  • 35
  • 65
M9A
  • 3,168
  • 14
  • 51
  • 79
  • 5
    Another one : http://stackoverflow.com/questions/1949259/how-do-you-remove-an-array-element-in-a-foreach-loop – Eric Lavoie Jun 29 '16 at 19:11

2 Answers2

5

You need to use the key from your foreach, and unset the variable directly (from the session):

foreach ($_SESSION['cart']  as $key => $arrays3) {
    if($arrays3['id'] == $id){
        unset($_SESSION['cart'][$key]);
    }
}

Unsetting $arrays3 or any of its children will only be effective until the next iteration of the foreach loop, when it will be set again.

scrowler
  • 24,273
  • 9
  • 60
  • 92
2

You are using a dangerous form of the foreach loop. You MUST always unset the reference variable after the loop:

foreach ($_SESSION['cart']  as &$arrays3) {}
unset($arrays3);

Otherwise things will break if that loop is used again.

And the reference really is not needed. foreach operates on a copy of the array, so changes to the key or value will not go back into the original array, but you can always access the original array, as shown in the answer of @scrowler.

Sven
  • 69,403
  • 10
  • 107
  • 109