How to sort AM/PM in Laravel

To sort a collection of data in Laravel by a string that represents AM/PM time, you can use the sortBy method and a custom sorting function. Here's an example: $times = collect(["10:00 PM", "9:00 AM", "12:00 PM", "1:00 AM"]); $sortedTimes = $times->sortBy(function ($time) { $parts = explode(" ", $time); $hour = intval($parts[0]); $minute = intval(explode(":", $parts[0])[1]); $ampm = $parts[1]; if ($ampm === "PM") { $hour += 12; } return sprintf("%02d:%02d", $hour, $minute); }); return $sortedTimes; This will return a sorted collection of times, such as: ["1:00 AM", "9:00 AM", "12:00 PM", "10:00 PM"]

Get The latest Coding solutions.

Subscribe to the Email Newsletter