Home >Backend Development >PHP Tutorial >Can `array_unique` Be Used to Remove Duplicate Objects?

Can `array_unique` Be Used to Remove Duplicate Objects?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 16:36:29215browse

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>

Output:

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

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

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!

Statement:
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