array_udiff_assoc() – Compute Array Difference with Index Check Using Callback Comparison
This article explains PHP’s array_udiff_assoc function, detailing its purpose of computing array differences with index checks using a user‑defined callback, describing its parameters and return value, and providing a complete example with class definition, custom comparison function, usage code, and resulting output.
The array_udiff_assoc() function in PHP calculates the difference between two arrays while also comparing their keys, using a user‑provided callback function to determine how values are compared.
Parameters: array $array1 – the first array; array $array2 – the second array; callable $data_compare_func – a callback that 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 containing all values from $array1 that are not present in any of the other arrays, with key comparison performed using the supplied callback.
Example:
<?php
class cr {
private $priv_member;
function __construct($val) {
$this->priv_member = $val;
}
public 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),
2 => new cr(-15)
);
$b = array(
"0.2" => new cr(9),
0 => new cr(22),
1 => new cr(3),
2 => new cr(4)
);
$result = array_udiff_assoc($a, $b, array('cr', 'comp_func_cr'));
print_r($result);
?>Output:
Array
(
[0.1] => cr Object
(
[priv_member] => 9
)
[0.5] => cr Object
(
[priv_member] => 12
)
[0] => cr Object
(
[priv_member] => 23
)
[1] => cr Object
(
[priv_member] => 4
)
[2] => cr Object
(
[priv_member] => -15
)
)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
