Is there a function similar to the array_unique method that operates on objects? Imagine having multiple arrays containing 'Role' objects. You want to combine them and remove any duplicates.
Array_unique can be applied to an array of objects with the SORT_REGULAR constant:
<code class="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:
<code class="php">Array ( [0] => MyClass Object ( [prop] => test1 ) [2] => MyClass Object ( [prop] => test2 ) )</code>
Visit http://3v4l.org/VvonH#v529 for a live demonstration.
Caution: This method utilizes the "==" comparison rather than the strict comparison ("==="). So, when comparing objects within the array, it examines each object's properties rather than comparing object identities (instances).
The above is the detailed content of Can `array_unique` Be Used to Remove Duplicate Objects?. For more information, please follow other related articles on the PHP Chinese website!