Unset an array item in a foreach loop

Trying to remove an item from a PHP foreach loop is not a straight forward job, because, PHP works on a copy of that array, so you need to do it like this:

$items = array('a','b','c','d');
foreach ($items as $key => $value) {
    if ($value=='b' || $value=='d') {
        unset($items[$key]);
    }
}
var_dump($items);

this outputs:

array(2) {
  [0]=>
  string(1) "a"
  [2]=>
  string(1) "c"
}

Leave a Reply

Your email address will not be published. Required fields are marked *

(Your message will only be visible after moderation)