views:

51

answers:

1

Hi! Is there any method like the array_unique for objects? I have a bunch of arrays with 'Role' objects that I merge, and then I want to take out the duplicates :)

Thanks

+4  A: 

Well array_unique() compares the string value of the elements:

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

So make sure to implement the __toString() method in your class and that it outputs the same value for equal roles, e.g.

class Role {
    private $name;

    //.....

    public function __toString() {
        return $this->name
    }

}

This would consider two roles as equal if they have the same name.

Felix Kling
thanks =) that seems to work just fine for me ;)
Johannes
@Jacob because neither `array_unique` nor `__toString()` compare anything. `__toString()` defines how an object instance is supposed to behave when used in a string context and `array_unique` returns the input array with duplicate values removed. It just *uses* comparison for this internally.
Gordon
@Jacob Relkin: It isn't comparator. It is the string representation of the object. I think they use this as you can convert any type, object, etc. into a string. But the string method itself on an object is not only used by this function. E.g. `echo $object` also uses the `__toString` method.
Felix Kling