How Can I Use `array_unique` to Remove Duplicate Objects in PHP?

Linda Hamilton
Release: 2024-11-01 04:13:02
Original
689 people have browsed it

How Can I Use `array_unique` to Remove Duplicate Objects in PHP?

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>
Copy after login

To remove duplicates using array_unique:

<code class="php">print_r(array_unique($test, SORT_REGULAR));</code>
Copy after login

Output:

Array (
    [0] => Role Object
        (
            [name] => test1
        )

    [2] => Role Object
        (
            [name] => test2
        )
)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!