hhvm icon indicating copy to clipboard operation
hhvm copied to clipboard

ksort() mishandles numeric strings with SORT_NUMERIC

Open jmarrama opened this issue 12 years ago • 4 comments

<?php
$arr = [];
$arr['67 - 96'] = 'FOO';
$arr['67 - 77'] = 'BAR';
ksort($arr, SORT_NUMERIC);
var_dump($arr);

/*
devVM:~/scratch/ksort]$ hhvm bug.php
array(2) {
    ["67 - 96"]=>
        string(3) "FOO"
    ["67 - 77"]=>
        string(3) "BAR"
}
devVM:~/scratch/ksort]$ php -f bug.php
  array(2) {
      '67 - 77' =>
          string(3) "BAR"
      '67 - 96' =>
          string(3) "FOO"
  }
 */

jmarrama avatar Apr 30 '14 01:04 jmarrama

@jmarrama Interesting corner case. However, I am not convinced this is necessarily a bug (or mishandling) with our ksort, more than a discrepancy on the order we output the values of an array in a special case like this.

With SORT_NUMERIC on strings, we convert toDouble. And in both array elements, toDouble() will return 67. So when we compare in the sorting algorithm, the keys will be equal (neither less than or greater than), so we will just return as is. PHP5, returns the ordering the other way, I guess.

https://github.com/facebook/hhvm/blob/master/hphp/runtime/base/sort-helpers.h#L110

Try this code...

<?php
$arr = [];
$arr['67 - 96'] = 'FOO';
$arr['67 - 97'] = 'BAR';
ksort($arr, SORT_NUMERIC);
var_dump($arr);

you get the same ordering as your example, even though you might expect the PHP5 to reverse the other way because the string comparison should return the opposite result.

I can argue that our way is right, actually. But regardless, the question here is to decide whether we want to match PHP5's behavior in this particular case.

cc:\ @jdelong , @ptarjan

JoelMarcey avatar Apr 30 '14 20:04 JoelMarcey

If, what @JoelMarcey says is right (which I have not verified), it's sort of the same issue as: https://github.com/facebook/hhvm/pull/2484

Hoping that the HHVM team allows me to implement it as a runtime option (it can be off by default for all I care), but I haven't had a conclusive answer yet. Maybe it's best if we focus the comm. in that ticket.

danslo avatar Apr 30 '14 20:04 danslo

It is the same issue, ksort in php just reverses this array so if you run it twice it will have same order as in hhvm.

Pomyk avatar May 01 '14 21:05 Pomyk

same as #2484

ptarjan avatar Jun 16 '14 08:06 ptarjan