PHP providing closure to determine the uniqueness of an element in an array

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

PHP provides this sorting using the usort () method - it's just interesting if it is available for uniqueness checking. Thank!

+3
source share
3 answers

array_filter, true/false , . , array_filter .

+1

, , , , , ...

$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
        )

)
0

array_unique() , , array_uunique() ( , , , PHP , ).

, foreach:

$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;
        }
    }
}
0
source

Source: https://habr.com/ru/post/1761995/


All Articles