views:

800

answers:

4

Hi, 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.

+1  A: 

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

Corey Sunwold
While it is bad practice in most languages, arrays in PHP are basically associative arrays that can be iterated in order. Deleting an earlier element does not change the keys of elements that come after it.
Ignacio Vazquez-Abrams
@Ignacio Thanks, I did not know that.
Corey Sunwold
Actually, it's allowed because the array that foreach uses internally is a copy of the original array. That way, modifying the original array is perfectly safe.
Juan
+7  A: 
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]);
        } 
    }
}
prodigitalson
It works perfectly. Thank you!
ecu
A: 

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.

paul.meier
+2  A: 

Try this:

foreach($array AS &$element) {
    foreach($element AS $key => $value) {
        if ($key == 'id' && $value == 'searched_value') {
            unset($element); // Now it works! :)
        } 
    }
}

Actually you can do this instead:

foreach($array AS $key => $element) {
    if (isset($element['id']) AND ($element['id'] == 'searched_value')) {
        unset($array[$key]);
    }
}
TiuTalk
Nope. This only unsets the local variable itself.
Ignacio Vazquez-Abrams
TiuTalk
Yes, even as a reference.
Ignacio Vazquez-Abrams