Hi I have an array with keys as date in this format.

$arr = array(

    "20110805" => "2",
    "20100703" => "5",
    "20110413" => "3",
    "20100805" => "4",
    "20100728" => "6",
    "20090416" => "7",
    "20080424" => "8",
    "20110819" => "1",  
);

how can I sort this array by key. Thank you.

share|improve this question
-1 Google: "PHP sort array by keys" – x3ro Aug 20 '11 at 21:26
-1 Google: "PHP sort array by keys" – TheHorse Aug 20 '11 at 21:31
@TheHorse - There are lots of things which can be found by googling. It's much preferred to show duplicates on SO than LMGTFY-type comments. :) – Jared Farrish Aug 20 '11 at 21:33
@Jared Farrish - SO SO SO simple question. i find answer at google with out php knowledge – TheHorse Aug 20 '11 at 21:36
@TheHorse - meta.stackoverflow.com/questions/15650/… The purpose of SO is to be a repository of information, regardless of the simplicity or complexity of the question and/or answer, as long as it fits in the rules found in the FAQ. If it's a duplicate or answered elsewhere on SO, linking to those answers are considered good etiquette. – Jared Farrish Aug 20 '11 at 21:44
show 1 more comment

2 Answers

up vote 8 down vote accepted

With the dates in that format, an alphabetical comparison will work just fine. Use the PHP function ksort.

ksort($arr);
share|improve this answer
2  
Example: codepad.org/5WjP74TR – Jared Farrish Aug 20 '11 at 21:26
hi thanks for your answer, ksort will sort the array by key but the key here are dates and ksort doesn't sort the array in order. i need to convert the keys to a valid date format and then do ksort, but doing that will affect the rest of the code. any suggestions?? – bharath Aug 20 '11 at 21:28
1  
@bharath - Your dates are in YEAR MONTH DAY order, which means you can sort them using a normal sort and it will put it in proper order, as long as you have 0's preprended to the short MONTHs and DAYs. Your "dates" are essentially just a number that can be parsed into a date. – Jared Farrish Aug 20 '11 at 21:31
With the data you've shown us no extra manipulation is needed, and the example Jared posted works. – coyotebush Aug 20 '11 at 21:33
@Jared Farrish - thanks, but if you look at the example in codepad you can see the order is still not right. how can i get to to be in date order? – bharath Aug 20 '11 at 21:34
show 4 more comments

Just this single line of code:

ksort($arr);
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.