Link to home
Start Free TrialLog in
Avatar of jrm213jrm213
jrm213jrm213Flag for United States of America

asked on

PHP - Delete Object from array while in a foreach loop iterating that array

Hi,

I am hoping this is a simple question with a simple answer that I am just not seeing.

I have an array of existing people objects, and an array of people objects that need to be removed from the list of existing people.

foreach($entity->removals as $removal){
    foreach($entity->existing_list as $existing){
        if($removal->get_id() == $existing->get_id()){
                //is there a simple way to remove $existing from $entity->existing_list
        }
    }
}

Open in new window

SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jrm213jrm213

ASKER

interesting so changing the structure of the foreach like that makes $key into the index of the array while putting the value into $existing. I didn't realize it worked that way. Thanks!
Thanks!
Thanks for the points.  You might find some value in this article...
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html

Best regards, ~Ray
yeah in the past when I wanted to modify the object for the current iteration I just made the for loop like this

foreach($list as &$list_item){
}

Open in new window


which would make list_item as a reference instead of a value, but that doesn't help when you need to remove $list_item from the list, it just lets you modify that item in the list.