Search code examples
phpforeachunsetarrays

How to delete object from array inside foreach loop?


I iterate through an array of objects and want to delete one of the objects based on it's 'id' property, but my code doesn't work.

foreach($array as $element) {
    foreach($element as $key => $value) {
        if($key == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($element);//this doesn't work
            unset($array,$element);//neither does this
        } 
    }
}

Any suggestions. Thanks.


Solution

  • foreach($array as $elementKey => $element) {
        foreach($element as $valueKey => $value) {
            if($valueKey == 'id' && $value == 'searched_value'){
                //delete this particular object from the $array
                unset($array[$elementKey]);
            } 
        }
    }