php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #54571 asort is not stable (mixes keys)
Submitted: 2011-04-20 00:12 UTC Modified: 2011-04-20 01:59 UTC
From: mightyuhu@php.net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.3.6 OS: any
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: mightyuhu@php.net
New email:
PHP Version: OS:

 

 [2011-04-20 00:12 UTC] mightyuhu@php.net
Description:
------------
In the manual it sais: "This function sorts an array such that array indices maintain their correlation with the array elements they are associated with."
But when we have the same value the order of the keys is swapped. (See Test Script). This is unexpected and kind of destroys the correlation.

In computer science terms one would say asort is not a stable sorting function.


Tested with:
- PHP 5.3.3-7+squeeze1 with Suhosin-Patch
- PHP 5.3.6
- PHP 5.3.5
- PHP 5.2.17

Test script:
---------------
<?php 
$testarray = array ('1' => (int) 23, '2' => (int) 1, '4' => (int) 1);
var_dump($testarray);
asort($testarray);
var_dump($testarray);
//4 and 2 are switched
?>

Expected result:
----------------
array(3) { [1]=> int(23) [2]=> int(1) [4]=> int(1) }
array(3) { [2]=> int(1) [4]=> int(1) [1]=> int(23) }

Actual result:
--------------
array(3) { [1]=> int(23) [2]=> int(1) [4]=> int(1) }
array(3) { [4]=> int(1) [2]=> int(1) [1]=> int(23) }

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-04-20 01:32 UTC] dtajchreber@php.net
-Status: Open +Status: Bogus
 [2011-04-20 01:32 UTC] dtajchreber@php.net
Known, documented, and not a bug.

[1] http://www.php.net/manual/en/array.sorting.php

"If any of these sort functions evaluates two members as equal then the order is 
undefined (the sorting is not stable)."

[2] http://lxr.php.net/opengrok/xref/PHP_5_3/ext/standard/array.c#490
[3] http://lxr.php.net/opengrok/xref/PHP_5_3/Zend/zend_qsort.c#56
 [2011-04-20 01:56 UTC] danvarin at googlemail dot com
Ok. Since this behavior seems to be documented, but there are other functions with 
"preserve_key" parameters, i'd like to make this a feature request.
 [2011-04-20 01:59 UTC] mightyuhu@php.net
-Type: Bug +Type: Feature/Change Request
 [2011-04-20 01:59 UTC] mightyuhu@php.net
Ok. Since this behavior seems to be documented, but there are other functions with 
"preserve_key" parameters, i'd like to make this a feature request.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 17:01:30 2024 UTC