Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2144
  • Last Modified:

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

0
jrm213jrm213
Asked:
jrm213jrm213
  • 3
  • 3
2 Solutions
 
Ray PaseurCommented:
You can use an array key in foreach(). Can you show us a bit of test data?
0
 
Ray PaseurCommented:
Untested but possibly correct...

foreach($entity->removals as $removal){
    foreach($entity->existing_list as $key => $existing){
        if($removal->get_id() == $existing->get_id()){
            unset($entity->existing_list[$key]);
        }
    }
}

Open in new window

0
 
jrm213jrm213Author Commented:
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!
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
jrm213jrm213Author Commented:
Thanks!
0
 
Ray PaseurCommented:
Thanks for the points.  You might find some value in this article...
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html

Best regards, ~Ray
0
 
jrm213jrm213Author Commented:
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.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now