Bug #76662 [Opn->Nab]: Issue sorting when values are equal
| From: | requinix@php.net | Date: | Wed, 25 Jul 2018 08:06:26 +0000 |
| Subject: | Bug #76662 [Opn->Nab]: Issue sorting when values are equal | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-216441@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=76662&edit=1
ID: 76662
Updated by: requinix@php.net
Reported by: panin dot alexei at gmail dot com
Summary: Issue sorting when values are equal
-Status: Open
+Status: Not a bug
Type: Bug
-Package: *General Issues
+Package: Arrays related
Operating System: OSX and UBUNTU
PHP Version: 7.0.31
Block user comment: N
Private report: N
New Comment:
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to
report
a bug at http://bugs.php.net/how-to-report.php
http://php.net/manual/en/function.usort.php
> Note:
> If two members compare as equal, their relative order in the sorted array is undefined.
PHP does not guarantee a stable sort.
Your example should compare the [0] elements as a secondary sort.
return ($a[1] <=> $b[1]) ?: ($a[0] - $b[0]); // $a[0] <=> $b[0] would compare as
strings
Previous Comments:
------------------------------------------------------------------------
[2018-07-25 08:01:17] panin dot alexei at gmail dot com
Description:
------------
---
From manual page: http://www.php.net/function.usort
---
Even when values are equal, they are mixed. The resulting / sorted array should be identical with
initial array, it;s not the case.
Test script:
---------------
<?php
$array = [
["1", 1],
["2", 1],
["3", 1],
["4", 1],
["5", 1],
["6", 1],
["7", 1],
["8", 1],
["9", 1],
["10", 1],
["11", 1],
["12", 1],
["13", 1],
["14", 1],
["15", 1],
["16", 1],
["17", 1],
["18", 1],
["19", 1],
["20", 1],
["21", 1],
["22", 1],
["23", 1],
["24", 1],
["25", 1],
["26", 1],
["27", 1],
["28", 1],
["29", 1],
["30", 1],
["31", 1],
["32", 1],
["33", 1],
["34", 1],
["35", 1],
["36", 1]
];
usort($array, function($a, $b){
return $a[1] <=> $b[1];
});
print_r($array);
Expected result:
----------------
array should bot be altered
Actual result:
--------------
array is sorted
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=76662&edit=1