Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate objects from arrays? [duplicate]

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 312
Johannes Avatar asked Nov 26 '22 15:11

Johannes


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 58
Matthieu Napoli Avatar answered Dec 10 '22 15:12

Matthieu Napoli