How to add minutes value in for loop PHP?

103 Views Asked by At

I have these for loop code that loop time and increase minute by 20+ minutes.

But I want to include also the starting time. Somehow it's missing in the output.

My current code :

$slot_count = 5;

$start = strtotime("08:00");

for( $i=0; $i<$slot_count; $i++ )
{
    $start  = $start;
    $end_new = date("H:i:s", strtotime('+20 minutes', $start));  
    $start  = strtotime($end_new);

    echo ''.$end_new.'<br/>';
    
} 

Current output :

08:20:00
08:40:00
09:00:00
09:20:00
09:40:00

Expected output :

08:00:00
08:20:00
08:40:00
09:00:00
09:20:00
09:40:00
1

There are 1 best solutions below

0
ADyson On

It's missing the first (starting) value simply because you don't echo anything until after you've calculated the second value.

An easy way to resolve that is just to add an extra echo before the loop:

$start = strtotime("08:00");
echo date("H:i:s", $start).'<br/>';

Demo: https://3v4l.org/TYJ6a

P.S. $start = $start is completely redundant, you're just re-assigning the variable to itself, you end up with the same thing you started with. The '' empty string in echo ''.$end_new.'<br/>'; also doesn't do anything useful either. I removed those in the demo code.