Voting

: min(seven, seven)?
(Example: nine)

The Note You're Voting On

falundir at gmail dot com
6 years ago
I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality (like array_udiff and array_uintersect). So, here's my version for you:

<?php
function array_uunique(array $array, callable $comparator): array {
$unique_array = [];
do {
$element = array_shift($array);
$unique_array[] = $element;

$array = array_udiff(
$array,
[
$element],
$comparator
);
} while (
count($array) > 0);

return
$unique_array;
}
?>

And here is a test code:

<?php
class Foo {

public
$a;

public function
__construct(int $a) {
$this->a = $a;
}
}

$array_of_objects = [new Foo(2), new Foo(1), new Foo(3), new Foo(2), new Foo(2), new Foo(1)];

$comparator = function (Foo $foo1, Foo $foo2): int {
return
$foo1->a <=> $foo2->a;
};

var_dump(array_uunique($array_of_objects, $comparator)); // should output [Foo(2), Foo(1), Foo(3)]
?>

<< Back to user notes page

To Top