PHP: how to sort an array by keys numerically?
Question
Even though I have read the PHP documentation and this looks like to be a FAQ, it's still giving me some headache.
I have an array like this which holds the months of the year:
[12] => december
[4] => april
[3] => march
[6] => june
[7] => july
[10] => october
...and so on
The order is not as it should be. I want to reorder the keys numerically. I can swap the keys with values if I want, but while each numerical value will match the corresponding month, they will never be in order. So I thought of putting these in order via PHP.
I have tried with $calendar = ksort( $myarray );
But If I try to print $calendar
, I will only get bool=true or array with a single key and "1" as value... I was planning to use the ksort result in a foreach later, but I can't.
What I'm droing wrong?
Solution
No .. just use:
ksort($myarray);
print_r($myarray)
ksort() sorts an array by key, maintaining key to data correlations, returns TRUE
on success or FALSE
on failure, if you associate the $calendar
with ksort()
you will have what ksort
returns.
OTHER TIPS
ksort($arr);
foreach ($arr as $key => $val)
{
echo "$key = $val\n";
}