note 125317 deleted from language.operators.comparison by cmb
| From: | cmb@php.net | Date: | Tue, 01 Sep 2020 15:08:51 +0000 |
| Subject: | note 125317 deleted from language.operators.comparison by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-215055@lists.php.net to get a copy of this message | ||
Note Submitter: vallier dot zac at gmail dot com
----
So I couldn't find an answer readily anywhere about what happens when using the spaceship
operator to sort data that contains null values in the mix so I wrote a test to prove that they are
handled as expected and sorted to the top/bottom.
$int_test = [8,4,2,null,5,null,12,384];
$str_test = ["foo", "bar", null, null, "zoo", "tam"];
$flt_test = [null, 1.54, 200.2222, 100.1, null, 55.55, 55.56, 55.54];
$icomp = function ($a, $b) {
$t1 = intval($a);
$t2 = intval($b);
return $t1 <=> $t2;
};
$scomp = function ($a, $b) {
$t1 = strval($a);
$t2 = strval($b);
return $t1 <=> $t2;
};
$fcomp = function ($a, $b) {
$t1 = floatval($a);
$t2 = floatval($b);
return $t1 <=> $t2;
};
usort($int_test, $icomp); // [null,null,2,4,5,8,12,384]
usort($str_test, $scomp); //
[null,null,"bar","foo","tam","zoo"]
usort($flt_test, $fcomp);
// [null,null,1.54,55.54,55.55,55.56,100.1,200.2222]