How to Remove Duplicate Objects from an Array in PHP?

Linda Hamilton
Release: 2024-11-04 08:49:02
Original
392 people have browsed it

How to Remove Duplicate Objects from an Array in PHP?

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

Output:

Array (
    [0] => MyClass Object
        (
            [prop] => test1
        )

    [2] => MyClass Object
        (
            [prop] => test2
        )
)
Copy after login

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!

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!