No NAME
No NAME

Reputation: 169

PHP: ksort return wrong result if use 0 before number

This is my code:

$array = [
    'd 01 x'=>'b',
    'd 3 x'=>'a',
    'd 02 x'=>'b',
    'd 9 x'=>'b',
    'd 8 x'=>'b',
    'd 07 x'=>'b',
    'd 10 x'=>'b'
];

ksort($array);
print_r($array);

And this is result:

Array ( [d 01 x] => b [d 02 x] => b [d 07 x] => b [d 10 x] => b [d 3 x] => a [d 8 x] => b [d 9 x] => b )

Why after d 02 x not showing d 3 x?

How I can fix it?

Thank you

Upvotes: 0

Views: 220

Answers (1)

Remy
Remy

Reputation: 807

You most likely want to use uksort for this. uksort allows you to supply your own function which it will use for sorting.

The following piece of code first defines a function to transform the string key into it's integer representation, and compares the two supplied items by using the space ship operator.

function toInt($element)
{
    return (int)str_replace(['d', ' ', 'x'], '', $element);
}

uksort($array, function ($first, $second) {
    $f = toInt($first);
    $s = toInt($second);

    return $f <=> $s;
});

print_r($array);

output:

Array
(
    [d 01 x] => b
    [d 02 x] => b
    [d 3 x] => a
    [d 07 x] => b
    [d 8 x] => b
    [d 9 x] => b
    [d 10 x] => b
)

Upvotes: 2

Related Questions