phpsortingksort

ksort produces wrong result when dealing with alphanumeric characters


<?php

    $a = array(
        'a'=>'7833',
        'd'=>'1297',
        'c'=>'341',
        '1'=>'67',
        'b'=>'225',
        '3'=>'24',
        '2'=>'44',
        '4'=>'22',
        '0'=>'84'
    );

    ksort($a);

    print_r($a);

The above code produces the following output.

Array
(
    [0] => 84
    [a] => 7833
    [b] => 225
    [c] => 341
    [d] => 1297
    [1] => 67
    [2] => 44
    [3] => 24
    [4] => 22
)

Why does ksort give wrong result?


Solution

  • You'll want to use the SORT_STRING flag. SORT_REGULAR would compare items with their current types, in which case the number 1 does come after the string 'a':

    php -r "echo 1 > 'a' ? 'yes' : 'no';" // yes