<?php
/**
* Remove duplicate elements from an array using a user-defined Reductor function.
* @param array $array
* @param callable $reductor Reduces a single array element to a simple type for 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;
}
}
);
}
$arr = [
[ 'target' => 'a' ],
[ 'target' => 'b' ],
[ 'target' => 'c' ],
[ 'target' => 'd' ],
[ 'target' => 'c' ],
[ 'target' => 'e' ],
];
echo json_encode( array_uunique($arr, function($a){return $a['target'];}), JSON_PRETTY_PRINT ) . PHP_EOL;
- Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- {
"0": {
"target": "a"
},
"1": {
"target": "b"
},
"2": {
"target": "c"
},
"3": {
"target": "d"
},
"5": {
"target": "e"
}
}
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
{
"0": {
"target": "a"
},
"1": {
"target": "b"
},
"2": {
"target": "c"
},
"3": {
"target": "d"
},
"5": {
"target": "e"
}
}
preferences:
162.82 ms | 402 KiB | 186 Q