Search code examples
phparraysforeachreferenceunset

Deleting an item in a foreach loop in PHP


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?


Solution

  • 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.