note 123460 added to function.array-udiff
| From: | (morales2k) | Date: | Thu, 20 Dec 2018 14:17:27 +0000 |
| Subject: | note 123460 added to function.array-udiff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209929@lists.php.net to get a copy of this message | ||
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
// Arrays to compare
$array1 = array(new stdclass, new stdclass,
new stdclass, new stdclass,
);
$array2 = array(
new stdclass, new stdclass,
);
// Set some properties for each object
$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!
----
Server IP: 208.43.231.9
Probable Submitter: 24.41.224.18
----
Manual Page -- http://php.net/manual/en/function.array-udiff.php
Edit -- https://master.php.net/note/edit/123460
Del: integrated -- https://master.php.net/note/delete/123460/integrated
Del: useless -- https://master.php.net/note/delete/123460/useless
Del: bad code -- https://master.php.net/note/delete/123460/bad+code
Del: spam -- https://master.php.net/note/delete/123460/spam
Del: non-english -- https://master.php.net/note/delete/123460/non-english
Del: in docs -- https://master.php.net/note/delete/123460/in+docs
Del: other reasons-- https://master.php.net/note/delete/123460
Reject -- https://master.php.net/note/reject/123460
Search -- https://master.php.net/manage/user-notes.php