Most of the earlier answers failed to acknowledge the available shortcut of comparing the datetime values as simple strings. Other answers that realized that strtotime()
was unnecessary did not spell out why did what they did ...so I will.
Because your datetime
values are formatted with units in descending size (Y
, m
, d
, H
, i
, s
) AND because each unit is consistently expressed with the same number of characters (4, 2, 2, 2, 2, 2) AND because the delimiting characters are all identical from string to string, you can simply compare them character-by-character from left to right (naturally). This would not be true for a date string formatted as, say, d/m/Y
.
There are two functions that are ideal for this task, I'll demonstrate ASC and DESC versions for both.
Demo Link
usort() by date column DESC:
usort($array, function($a, $b) { return $b['datetime'] <=> $a['datetime']; });
usort() by date column ASC:
usort($array, function($a, $b) { return $a['datetime'] <=> $b['datetime']; });
usort() by date column ASC in >= PHP7.4:
usort($array, fn($a, $b) => $a['datetime'] <=> $b['datetime']);
array_multisort() by date column DESC:
array_multisort(array_column($array, 'datetime'), SORT_DESC, $array);
array_multisort() by date column ASC:
array_multisort(array_column($array, 'datetime'), $array);
All of these techniques modify by reference, so the function provide no real valuable return value.
array_multisort()
:
- doesn't need a custom function
- it does need the datetime column to be isolated by some looping mechanism
- it will lose numeric keys, but fortunately they are not valuable for this question
usort()
:
- doesn't use sorting direction constants, so developers must understand that
$a
before $b
(on either side of the spaceship operator) means ASC and $b
before $a
means DESC
- requires a custom function
- can be adjusted to preserve first level keys by calling
uasort()
instead
For anyone who truly DOES need a date or datetime string to be parsed because its format does not permit instant string comparisons, here is an answer devoted to explaining the caveats of that task.