note 123122 deleted from function.usort by cmb
| From: | cmb@php.net | Date: | Sun, 13 Oct 2019 08:16:29 +0000 |
| Subject: | note 123122 deleted from function.usort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212635@lists.php.net to get a copy of this message | ||
Note Submitter: Patrick
----
Note that
<?php
$array = ['valA', 'valB', 'valC'];
$x = 1; /* this means valA > valC (try -1 for valA < valC) */
usort($array, function($val1, $val2) use ($x) {
if ($val1 == 'valA' && $val2 == 'valB') return (0);
if ($val1 == 'valA' && $val2 == 'valC') return ($x);
if ($val1 == 'valB' && $val2 == 'valC') return (0);
});
print_r($array); // result: [valA, valB, valC]
?>
will lead to the same (potentially unintended) result ([valA, valB, valC]), regardless of whether
$x=1 or $x=-1.
This is because PHP only compares the pairs (valA, valB) and (valB, valC) if it finds that both of
them are supposed to be equal, as it assumes the sorting function to be transitive.