I find it that this is an ideal place to apply the spaceship operator, but it was not used in the examples.
Here is Example#1 using the spaceship operator in the comparison function.
<?php
$array1 = array(new stdclass, new stdclass,
new stdclass, new stdclass,
);
$array2 = array(
new stdclass, new stdclass,
);
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7; $array1[1]->height = 1;
$array1[2]->width = 2; $array1[2]->height = 9;
$array1[3]->width = 5; $array1[3]->height = 7;
$array2[0]->width = 7; $array2[0]->height = 5;
$array2[1]->width = 9; $array2[1]->height = 2;
function compare_by_area($a, $b) {
$areaA = $a->width * $a->height;
$areaB = $b->width * $b->height;
return $areaA <=> $areaB;
}
print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>
The output is:
Array
(
[0] => stdClass Object
(
[width] => 11
[height] => 3
)
[1] => stdClass Object
(
[width] => 7
[height] => 1
)
)
I find it is pretty awesome you can substitute all of these lines:
if ($areaA < $areaB) {
return -1;
} elseif ($areaA > $areaB) {
return 1;
} else {
return 0;
}
with just:
return $areaA <=> $areaB;
Neat!