Using array_udiff() with a Callback Function to Compute Array Differences in PHP
This article explains how the PHP function array_udiff() works with a user‑defined comparison callback to return the elements present in the first array but absent from subsequent arrays, includes parameter details, return behavior, and a complete runnable example with output.
array_udiff() returns an array containing all values from array1 that are not present in any of the other arrays, while preserving the original keys. The comparison of values is performed by a user‑defined callback function supplied as data_compare_func .
Parameters :
array1 – the first array.
array2 – the second array (additional arrays can be passed).
data_compare_func – a callable that receives two values and must return an integer less than, equal to, or greater than zero when the first argument is considered less than, equal to, or greater than the second.
Return value : an array of the values from array1 that are not found in any of the other arrays, with their original keys preserved.
Example implementation :
priv_member = $val;
}
static function comp_func_cr($a, $b) {
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member) ? 1 : -1;
}
}
$a = array(
"0.1" => new cr(9),
"0.5" => new cr(12),
0 => new cr(23),
1 => new cr(4)
);
$b = array(
"0.2" => new cr(9),
"0.5" => new cr(12),
0 => new cr(3),
1 => new cr(4),
2 => new cr(-15)
);
$result = array_udiff($a, $b, "cr::comp_func_cr");
print_r($result);
?>The script prints the resulting array, showing the elements that are unique to $a according to the custom comparison logic. In this case the output is:
Array
(
[0.5] => cr Object
(priv_member => 12)
[0] => cr Object
(priv_member => 23)
)Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.