Wallogit.com
2017 © Pedro Peláez
array_uunique() FunctionThere are various workarounds to get this functionality, and this is one of them!, (*1)
<?php
if( ! function_exists('array_uunique') ) {
/**
* Remove duplicate elements from an array using a user-defined Reductor
* @param array $array
* @param callable $reductor Reduces a single array element to a simple type for strict equivalence checking.
*/
function array_uunique(array $array, callable $reductor) {
$seen = [];
return array_filter(
$array,
function($a)use(&$seen, $reductor){
$val = $reductor($a);
if( ! in_array($val, $seen, true) ) {
$seen[] = $val;
return true;
} else {
return false;
}
}
);
}
}
<?php
require('vendor/autoload.php');
$arr = [
[ 'target' => 'a' ],
[ 'target' => 'b' ],
[ 'target' => 'c' ],
[ 'target' => 'd' ],
[ 'target' => 'c' ],
[ 'target' => 'e' ],
];
var_dump( array_uunique($arr, function($a){return $a['target'];}) );
array(5) {
[0]=>
array(1) {
["target"]=> string(1) "a"
}
[1]=>
array(1) {
["target"]=> string(1) "b"
}
[2]=>
array(1) {
["target"]=> string(1) "c"
}
[3]=>
array(1) {
["target"]=> string(1) "d"
}
[5]=>
array(1) {
["target"]=> string(1) "e"
}
}
The Reductor is a function to take a complex type [eg: an array or object] and reduce it to a simple type [eg: a string or an integer] so that a simple, strict comparison can be performed., (*2)
If there's a better suited name for this kind of function please let me know., (*3)
n*log(n)
:I
http://grokbase.com/t/php/php-internals/13b7qvy12m/array-unique-optional-compare-callback-proposal#20131120g1r6r48hkgdx81nd27v6gjmdmr, (*4)
TL;DR: "It looks like a typo, and would require as much work as similar functions that were already implemented.", (*5)
Gimme a break., (*6)