Sort array of time strings naturally

Viewed 143

I need to sort an array of time strings (which are not zero padded) naturally.

Sample data:

$totlahourdat1 = ["9:30", "15:00", "13:00"];

When I try array_multisort($totlahourdat1, SORT_DESC), the data appears unchanged.

My actual code:

while($row11 = mysqli_fetch_array($hourget))
{
    $totlahourdat1[] = strtotime($row11['hours']); 
}   

array_multisort($totlahourdat1, SORT_DESC);

foreach ($totlahourdat1 as $time) {
    $totlahourdat[] = date("h:i",$time);
}

echo "<pre>";
    var_dump($totlahourdat);
echo "</pre>";

Ultimately, the array data should be ordered from earliest time to latest time:

["9:30", "13:00", "15:00"]
5 Answers

You do not need to parse these time expressions with strtotime() or a datetime method. Just sort naturally.

Code: (Demo)

sort($totlahourdat1, SORT_NATURAL);
Related