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';
Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
14:00

preferences:
139.32 ms | 407 KiB | 5 Q