1

I have a foreach loop where I want to unset an item from an array if certain conditions are met, like this:

foreach ($array as $element) {
    if (conditions) {
        unset($element);
    }
}

But the element is not unset after that. What am I doing wrong? Am I unsetting a reference to the actual element or something like that?

Eric Lavoie
  • 5,121
  • 3
  • 32
  • 49
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • Do you care if the index is still set? `$array[4]=NULL !== !isset($array[4])` – Shad Jan 21 '12 at 17:55
  • 1
    `unset` does 2 different things. If you had used `foreach($array as &$element)` (note the ampersand), then you would have replaced the value with null, which is the other behavior than the one you may be after: removing the item from the array entirely, without a trace. – bart Jan 21 '12 at 19:06

2 Answers2

8

Simple Solution, unset the element by it's index:

foreach ($array as $key => $element) {
    if (conditions) {
        unset($array[$key]);
    }
}

Just unsetting $element will not work, because this variable is not a reference to the arrays element, but a copy. Accordingly changing the value of $element will not change the array too.

DerVO
  • 3,679
  • 1
  • 23
  • 27
0

An alternate method, you can pass the array element into the loop by reference by doing the following:

foreach($array as &$var) {
    unset($var);
}

This is useful because you then have direct access to the array element to change or delete as you wish without having to construct a new array or accessing by key. Any changes you make to $var affects the contents of $array.

Gabriel Alack
  • 472
  • 2
  • 6
  • 16