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:
class Role {
public $name;
}
$foo = new Role();
$foo->name = 'test1';
$bar = $foo;
$bam = new Role();
$bam->name = 'test2';
$test = array($foo, $bar, $bam);
To remove duplicates using array_unique:
print_r(array_unique($test, SORT_REGULAR));
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3