php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76662 Issue sorting when values are equal
Submitted: 2018-07-25 08:01 UTC Modified: 2018-07-25 08:06 UTC
From: panin dot alexei at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 7.0.31 OS: OSX and UBUNTU
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
7 + 31 = ?
Subscribe to this entry?

 
 [2018-07-25 08:01 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-07-25 08:06 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: *General Issues +Package: Arrays related
 [2018-07-25 08:06 UTC] requinix@php.net
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
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 17:01:30 2024 UTC