Can the in_array
function compare objects?
For example, I have an array of objects and I want to add them distinctly to another array. Is it possible t
I've come up with a somewhat different, I think more robust, option.
function array_add_unique(&$array, $new, $test, $cb) {
if(is_array($array) && count($array)>0) {
for($i = 0; $i < count($array); $i++) {
if( $array[$i][$test] == $new[$test] ) {
$do = $cb($array[$i], $new);
if(is_bool($do) && $do) { $array[$i] = $new; }
else if(!is_bool($do)) { $array[$i] = $do; }
return;
}
}
}
array_push($array, $new);
}
The benefit to this solution, is it includes a user definable callback to handle collisions. When your adding unique objects, you may want to preserve properties from both the old and the new object.
The callback, which can be an anonymous function, receives both the new object and the existing object so the user can have a custom calculation. Return true to simply replace the existing object, or return a new object (non-bool) to replace it.
I do not know the performance of this on large datasets though.