Unique Objects with array_unique
In PHP, the array_unique function assists in eliminating duplicate values from an array. However, when working with arrays containing objects, this functionality may not seem to work as expected.
Enter a Solution:
For arrays of objects, you can utilize array_unique with the SORT_REGULAR comparison flag. This flag instructs the function to compare objects by their properties rather than their object references.
Implementation:
Consider an array of Role objects:
<code class="php">class Role { public $name; } $foo = new Role(); $foo->name = 'test1'; $bar = $foo; $bam = new Role(); $bam->name = 'test2'; $test = array($foo, $bar, $bam);</code>
To remove duplicates using array_unique:
<code class="php">print_r(array_unique($test, SORT_REGULAR));</code>
Output:
Array ( [0] => Role Object ( [name] => test1 ) [2] => Role Object ( [name] => test2 ) )
Caution:
It's essential to note that array_unique with SORT_REGULAR uses the "==" comparison, not the strict comparison ("==="). This means that objects with identical properties but different object references will still be considered duplicates.
The above is the detailed content of How Can I Use `array_unique` to Remove Duplicate Objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!