How to delete object from array inside foreach loop? How to delete object from array inside foreach loop? arrays arrays

How to delete object from array inside foreach loop?


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]);        }     }}


You can also use references on foreach values:

foreach($array as $elementKey => &$element) {    // $element is the same than &$array[$elementKey]    if (isset($element['id']) and $element['id'] == 'searched_value') {        unset($element);    }}


It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.

The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.