phparrayssortingkeyksort

Sort array by keys which are in Ymd format with no delimiting characters


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?


Solution

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

    ksort($arr);