3v4l.org

run code in 300+ PHP versions simultaneously
<?php $timeslots = ["01:00","01:30","02:00","02:30","00:30","01:00","01:30","02:00","02:30","03:50", "14:00", "15:00", "15:30"]; sort($timeslots); // first we sort the array, very important $expected_time = "04:00"; $timestamp = strtotime($expected_time); $diff = PHP_INT_MAX; $index = null; foreach ($timeslots as $key => $time) { $currDiff = $timestamp - strtotime($time); // Add a condition to check if the difference was negative or not - because it'll only be the "next" hour when the difference is negative if ($currDiff < $diff && $currDiff < 0) { $index = $key; $diff = $currDiff; break; } } if(!is_null($index)) echo $timeslots[$index]; else echo 'Not found';

preferences:
24.15 ms | 405 KiB | 5 Q