Can `array_unique` Be Used to Remove Duplicate Objects?

Patricia Arquette
Release: 2024-11-02 16:36:29
Original
196 people have browsed it

Can `array_unique` Be Used to Remove Duplicate Objects?

Can Array_unique Be Used with Objects?

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.

Solution

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

Output:

<code class="php">Array (
    [0] => MyClass Object
        (
            [prop] => test1
        )

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

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!

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