php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #764 ksort mixes the implicit variable types and result is unexpected.
Submitted: 1998-09-21 13:29 UTC Modified: 1998-09-21 16:07 UTC
From: libs at cybercable dot tm dot fr Assigned:
Status: Closed Package: Misbehaving function
PHP Version: 3.0.3 OS: Linux
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: libs at cybercable dot tm dot fr
New email:
PHP Version: OS:

 

 [1998-09-21 13:29 UTC] libs at cybercable dot tm dot fr
<?
$toto["001"]="a";
$toto["010"]="c";
$toto[(string)"100"]="d";
$toto["002"]="b";
$toto["110"]="e";
 
ksort($toto);
for(reset($toto); $test = key($toto); next($toto)) {
  echo ($test." (".gettype($test).") : ".$toto[$test]."<BR>\n");
};
?>

gives
100 (integer) : d<BR>
110 (integer) : e<BR>
001 (string) : a<BR>
002 (string) : b<BR>
010 (string) : c<BR>

instead of :
001 (whatever) : a<BR>
002 (whatever) : b<BR>
010 (whatever) : c<BR>
100 (whatever) : d<BR>
110 (whatever) : e<BR>

It is agreed that it is not a bug, but the intended functionality is still
not available.

To make it available at some later time, I would suggest putting either
kasort() or kusort() in some TODO list.
By kasort() I mean a variation of ksort() which only considers the
string value in the sorting comparisons. It wouldn't have to change the
types of keys inside the array, just sort them in another way.
By kusort() I mean to do something like:
function cmp($a,$b) {
  if($a==$b) return 0;
  return ((string)$a>(string)$b) ? 1:-1;
}
kusort($toto, cmp):


[config irrelevant]

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [1998-09-21 16:07 UTC] zeev
This is the correct behavior.
Strings that look like numbers are automatically
converted to numbers in array indices, so 
$foo["5"] is identical to $foo[5].

This isn't the case for strings with leading zeros,
that is, $foo["01"] is not the same as $foo["1"] or
$foo[1].  This is why you get this behavior.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed May 15 16:01:35 2024 UTC