How to Remove Duplicate Objects from an Array in PHP
The array_unique() function can identify and eliminate duplicate elements from an array. However, this functionality may not be immediately apparent for arrays containing objects. To effectively remove duplicate objects, certain modifications are necessary.
Solution Using SORT_REGULAR
To enable array_unique() to work correctly with objects, specify the SORT_REGULAR flag as the second parameter:
<code class="php"><?php 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)); ?></code>
Output:
Array ( [0] => MyClass Object ( [prop] => test1 ) [2] => MyClass Object ( [prop] => test2 ) )
Explanation
By using SORT_REGULAR, the array_unique() function essentially compares the prop property of each object, treating objects with identical property values as duplicates.
Caution
While this method effectively removes duplicate objects, it's important to note that it relies on the == comparison rather than the stricter === comparison. This means that objects with different identities but identical properties will still be considered duplicates.
The above is the detailed content of How to Remove Duplicate Objects from an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!