3
1

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.

flag

4 Answers

6
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]);
        } 
    }
}
link|flag
It works perfectly. Thank you! – ecu Feb 21 at 3:02
1

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.

link|flag
1  
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 Feb 21 at 3:02
@Ignacio Thanks, I did not know that. – Corey Sunwold Feb 21 at 3:02
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 Feb 21 at 3:07
1

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]);
    }
}
link|flag
Nope. This only unsets the local variable itself. – Ignacio Vazquez-Abrams Feb 21 at 3:03
@Ignacio V. - Even using the &$element reference thing? – TiuTalk Feb 21 at 3:04
Yes, even as a reference. – Ignacio Vazquez-Abrams Feb 21 at 3:08
0

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.

link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.