Re: Unexpected results using ksort on arrays in which the keys are mixed alphanumeric strings.
| From: | Jochem Maas | Date: | Tue, 24 Feb 2009 09:25:25 +0000 |
| Subject: | Re: Unexpected results using ksort on arrays in which the keys are mixed alphanumeric strings. | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-288730@lists.php.net to get a copy of this message | ||
Clancy schreef:
> I have been experimenting using four character alphanumeric keys on an array, and when I
> generated a random set of keys, and then used ksort to sort the array, I was very
> surprised to find that if the key contained any non-numeric character, or if it started
> with zero, the key was sorted as a base 36 number (0- 9, A-Z, as I expected. However if
> the key only contained numbers, and did not start with zero, it was sorted to the end of
> the list.
did your experiment include reading the manual? or did you expect ksort() to known what
kind of sort you wanted? ... try specifying a sort flag:
<?php
$r = array(
'ASDF' => true,
'000A' => true,
'0009' => true,
'0999' => true,
'0000' => true,
'09A0' => true,
'9999' => true,
'1000' => true,
'ZZZZ' => true,
);
echo "UNSORTED:\n";
print_r($r);
echo "SORT_REGULAR:\n";
ksort($r, SORT_REGULAR);
print_r($r);
echo "SORT_NUMERIC:\n";
ksort($r, SORT_NUMERIC);
print_r($r);
echo "SORT_STRING:\n";
ksort($r, SORT_STRING);
print_r($r);
>
> Thus:
> 0000
> 0009
> 000A
>
> 0999
> 09A0
> ASDF
>
> ZZZZ
> 1000
> 9999
>
> I presume this is related to last weeks discussions about casting variables, but I cannot
> understand why 0999 should go to the start of the list, while 1000 goes to the end. Can
> anyone explain this logically?
>