2

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?

2 Answers 2

4

No .. just use:

ksort($myarray);
print_r($myarray)

Codepad example

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I just got that - I didn't understand what the PHP manual was trying to say and assumed I had to store the sorted array into a variable
0
ksort($arr);
foreach ($arr as $key => $val) 
{ 
   echo "$key = $val\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.