1

I need to exclude elements of the array $tempobjects from the array $objects. What is the quickest way to do this?

$objects = new MyObjects();
$tempobjects = new MyObjects();

for($i=0; $i<10; $i++) {
  $objects->addObject(new MyObject(...));
}

//...fill $tempobjects with some temporary data

$tempobjects = $objects - $tempobjects; // HOW TO DO SOMETHING LIKE THIS?
9
  • 1
    Looks like $objects and $tempObjects are objects (or objects that comprise a collection of data) rather than arrays Commented May 16, 2013 at 16:04
  • array_diff or array_diff_assoc are the usual ways to do this for arrays, but as mark baker said, you have objects, so those functions probably won't work. try converting your objects to arrays. Commented May 16, 2013 at 16:06
  • Possible duplicate of PHP: remove duplicate items in an array Commented May 16, 2013 at 16:06
  • @sgroves do you know if it would work if both of the objects in question implemented the ArrayAccess Interface? Commented May 16, 2013 at 16:07
  • @Anigel, in this case is not an array... Maybe he will need to add a method on the class that does this for him. Commented May 16, 2013 at 16:07

1 Answer 1

2

If $tempobjects and $objects were arrays (like your title mentions), which based on your sample code they are not, you could exclude elements using functions array_diff() (for comparing values) or array_diff_key() (for comparing keys).

See, also, this short demo.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.