views:

29

answers:

3

Quick question: is there a way to provide a closure in PHP to some equivalent function to the array_unique function so that you can specify your own comparison closure to be used when comparing two items in the array? I have an array of class instances (which may contain duplicates) and want to tell PHP to use particular logic to determine uniqueness.

PHP provides this with sorting using the usort() method - just wondering if it is also available for uniqueness checks. Thanks!

A: 

I couldn't find exactly what you are looking for but i thought maybe it wouldn't be too tough to write your own function...

$a = new StdClass;
$b = new StdClass;
$c = new StdClass;
$d = new StdClass;

$a->a = 1;
$b->a = 1;
$c->c = 1;
$d->c = 1;

$objects = array( $a,$b,$c,$d );

function custom_array_unique( array $objects ) {

    foreach( $objects as $k =>$object ) {
        foreach( $objects as $k2 => $object2 ) {

            if ( $k !== $k2 && $object == $object2 ) {
                unset( $objects[$k] );
            }

        }
    }
    return $objects;
}

print_r( custom_array_unique($objects));


Array
(
    [1] => stdClass Object
        (
            [a] => 1
        )

    [3] => stdClass Object
        (
            [c] => 1
        )

)
Galen
A: 

The manual page for array_unique() doesn't provide any links to a callback version, and there isn't a function in the list of links on the left called array_uunique() (which is what such a function should be called if it follows the naming convention of the other array sorting functions - but then PHP isn't very reliable when it comes to function naming conventions).

You could add this functionality yourself using a double foreach loop:

$uniqueness_fails = false;
foreach ( $myarray as $keyA => $valueA ) {
    foreach ( $myarray as $keyB => $valueB ) {
        if ( $keyA != $keyB and my_equality_function($valueA, $valueB) ) {
            $uniqueness_fails = true;
            break 2;
        }
    }
}
Hammerite
+1  A: 

there is array_filter that you can apply a callback to each element in an array and return true/false of whether to keep that value in the returning array. Here is a comment using array_filter to remove duplicates in an array.

Jonathan Kuhn