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?
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • 1
    Looks like $objects and $tempObjects are objects (or objects that comprise a collection of data) rather than arrays – Mark Baker May 16 '13 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. – user428517 May 16 '13 at 16:06
  • Possible duplicate of [PHP: remove duplicate items in an array](http://stackoverflow.com/questions/5036403/php-remove-duplicate-items-in-an-array) – Anigel May 16 '13 at 16:06
  • @sgroves do you know if it would work if both of the objects in question implemented the ArrayAccess Interface? – Orangepill May 16 '13 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. – Henrique Barcelos May 16 '13 at 16:07
  • @orangepill they might, but i'm not sure. i doubt it. – user428517 May 16 '13 at 16:08
  • @HenriqueBarcelos Indeed you are correct, I made the mistake of looking at what was asked rather than what the code said. – Anigel May 16 '13 at 16:10
  • @sgroves just confirmed you where right... gives a warning "Argument #1 in not an array" :( – Orangepill May 16 '13 at 16:20
  • try typecasting your objects to arrays, e.g. `$new_objects = (array) $objects;` – user428517 May 16 '13 at 16:22

1 Answers1

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.

gkalpak
  • 47,844
  • 8
  • 105
  • 118