Amir Soleymani Amir Soleymani - 1 year ago 105
PHP Question

PHP Time loop between start time and end time

I have this function that gives me a set of options in a select input.
The options give me times with 5 minute interval.
The problem is when the time is like 23:45, the options will start from 00:10 and loops based on the $j variable.

This is what I want to do in words:
Give me a list of options in 5 minutes interval from $open_time till $close_time.
If the current Time ($timeNow) is greater than the $open_time, set the $open_time to the $timeNow to be shown as first option.
Do this loop only until the $close_time.

I hope this is clear.
Appreciate your help :)

Here is the code:

function selectTimesofDay(){
$output = "";
$now = date('G:i ', time()); // time now
$timeNow = strtotime($now); // strtotime now
$next_five = ceil($timeNow / 300) * 300; // get next 5 minute
// time now rounded to next 10 minute
$round5minNow = date('G:i', strtotime('+15 minutes',$next_five));
$open_time = strtotime('17:00');
$close_time = strtotime('23:59');

// in the middle of working hours, time sets to current
if($timeNow >= $open_time && $timeNow < $close_time){
$open_time = strtotime($round5minNow);
$time_diff = round(($close_time - $open_time)/60) ;
if(date('l') == 'Friday'){
$j = ($time_diff/5)+11; // working hours extended untill 1:00 AM
} else{
$j = ($time_diff/5)-1; // working hours untill 12:00 AM

for($i = 0; $i <= $j; $i++){
$b = $i*5;
$data = date('l')." - ".date("H:i", strtotime('+'.$b.' minutes', $open_time));
$output .= "<option value=\"{$data}\">";
$output .= $data;
$output .= "</option>";

return $output;

Answer Source

What you really need is:

function selectTimesOfDay() {
    $open_time = strtotime("17:00");
    $close_time = strtotime("23:59");
    $now = time();
    $output = "";
    for( $i=$open_time; $i<$close_time; $i+=300) {
        if( $i < $now) continue;
        $output .= "<option>".date("l - H:i",$i)."</option>";
    return $output;

So what this does is run a loop checking every five-minute interval between opening and closing. Skip it if it is before the curent time, and otherwise add an option.

It's much more efficient than what you were trying to do, and probably easier to understand too.

You can even put this after the loop:

if( $output == "") return "<option disabled>Sorry, we're closed for today</option>";

Also, notice how I left out the value attribute all the time. That's because in the absence of a value, the option's text is used as a value. Thus this solution avoids needless duplication.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download