php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72643 rsort changed in php7
Submitted: 2016-07-22 01:25 UTC Modified: 2016-07-22 01:51 UTC
From: bpearson at squiz dot com dot au Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 7.0.9 OS: Centos
Private report: No CVE-ID: None
 [2016-07-22 01:25 UTC] bpearson at squiz dot com dot au
Description:
------------
Not sure if this is a bug or something to do with the changes in php7, but I cannot seem to find anything documentation wise about any change. I found that running rsort on a multi-dimensional array doesn't behave like it in older versions. If this is a change with php7 then there should be some form of documentation on sort() or rsort() page on php.net.

Demo: https://3v4l.org/7RdrB


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-07-22 01:51 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2016-07-22 01:51 UTC] requinix@php.net
PHP 7 did change how sorting sometimes works, but it has never promised anything more than a sorted result - so long as the comparison method used is reliable. That means exactly one of $a<$b, $a==$b, and $a>b must always be true for each pair of array elements $a,$b that can be compared. If the comparison method is not reliable then the result is undefined.

PHP 7 also uses a more stable sort, meaning that two equal items will probably appear in the same order in the output as they did in the input. PHP 5 didn't do that and they would often be shuffled around.

The bug here is that your array is not sortable using the "normal" comparison method because those two subarrays are not comparable.
  https://3v4l.org/G1J0B
See how all three of the tests show false? That means you'll get an undefined sort order in the final "sorted" array. It only changed with PHP 7 by sheer luck.

To properly sort that array you need to use usort() with a custom comparison function <https://3v4l.org/HZXON> or to use array_multisort() with a separate array that is sortable <https://3v4l.org/BarYS>.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 11:01:28 2024 UTC