Entry
Why does sort() return things not sorted?
Why are my numbers from a database sorted in alphabetical order not numerical?
Sep 11th, 2002 12:17
Dan Stockton, Nathan Wallace, Nathan Wallace, Tom Henry
PHP treats the values from a database as strings by default. That means
that if you get numbers out, they will be treated as strings that just
happen to contain digits and they will be sorted in alphabetical order.
You can try changing them to numbers in a loop over your array using:
$a[$i] = intval($a[$i]);
http://www.php.net/manual/function.intval.php3
You could also use PHP's settype directive to force the "type" for all
processing on a page for that varname
Of course, for complex projects you can place all the settype directives
into a autoprepend file -- because I'll forever be forgetting about the
retyping that's needed on numerics from the database queries.
Here's the DOCs on that
http://www.php.net/manual/function.settype.php3
You might also want natsort()
http://www.php.net/manual/function.natsort.php