Re: Unexpected results using ksort on arrays in which the keys are mixed alphanumeric strings.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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?
> 


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux