Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_unique for objects?

Is there any method like the array_unique for objects? I have a bunch of arrays with 'Role' objects that I merge, and then I want to take out the duplicates :)

like image 237
Johannes Avatar asked Mar 11 '10 16:03

Johannes


People also ask

How do you make an array of objects unique in PHP?

array_unique works by casting the elements to a string and doing a comparison. Unless your objects uniquely cast to strings, then they won't work with array_unique. Instead, implement a stateful comparison function for your objects and use array_filter to throw out things the function has already seen.

How to get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);

How to get duplicate value from array in PHP?

And a case-insensitive solution: $iArr = array_map('strtolower', $arr); $iArr = array_intersect($iArr, array_unique(array_diff_key($iArr, array_unique($iArr)))); array_intersect_key($arr, $iArr);


1 Answers

array_unique works with an array of objects using SORT_REGULAR:

class MyClass {     public $prop; }  $foo = new MyClass(); $foo->prop = 'test1';  $bar = $foo;  $bam = new MyClass(); $bam->prop = 'test2';  $test = array($foo, $bar, $bam);  print_r(array_unique($test, SORT_REGULAR)); 

Will print:

Array (     [0] => MyClass Object         (             [prop] => test1         )      [2] => MyClass Object         (             [prop] => test2         ) ) 

See it in action here: http://3v4l.org/VvonH#v529

Warning: it will use the "==" comparison, not the strict comparison ("===").

So if you want to remove duplicates inside an array of objects, beware that it will compare each object properties, not compare object identity (instance).

like image 178
Matthieu Napoli Avatar answered Sep 24 '22 14:09

Matthieu Napoli