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.
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]);
}
}
}
Be careful with the main answer.
with
[['id'=>1,'cat'=>'vip']
,['id'=>2,'cat'=>'vip']
,['id'=>3,'cat'=>'normal']
and calling the function
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'cat' && $value == 'vip'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}
it returns
[2=>['id'=>3,'cat'=>'normal']
instead of
[0=>['id'=>3,'cat'=>'normal']
It is because unset does not re-index the array.
It reindexes. (if we need it)
$result=[];
foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
$found=false;
if($valueKey === 'cat' && $value === 'vip'){
$found=true;
$break;
}
if(!$found) {
$result[]=$element;
}
}
}