How to delete object from array inside foreach loop?
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.
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;
}
}
}
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]);
}
}
}
This should do the trick.....
reset($array);
while (list($elementKey, $element) = each($array)) {
while (list($key, $value2) = each($element)) {
if($key == 'id' && $value == 'searched_value') {
unset($array[$elementKey]);
}
}
}