Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop incrementing time by 45 minutes

Tags:

php

for-loop

I know i can do a normal loop with whole integers like this

for($i=0;$i<10;$i++)
{
   echo $i;
}

Problem:
I want to loop through a loop not with whole numbers but with floats times ( 45 minutes ). I want the results to be like this:

0.45
1.30
2.15
3.00
3.45
...

Is there any helper function in PHP to achieve that?

like image 631
intelis Avatar asked Dec 07 '22 10:12

intelis


2 Answers

Reading the comments and seeing that you actually want to work with times, you can even use a DateTime object inside a for loop

Here is some example code:

for (
    $d = new DateTime('00:00'), // Initialise DateTime object .
    $i = new DateInterval('PT45M'); // New 45 minute date interval
    $d->format('H') < 10; // While hours (24h) less than 10
    $d->add($i) // Add the interval to the DateTime object
)
{
    echo $d->format("H:i\n");
}
like image 166
Leigh Avatar answered Dec 26 '22 06:12

Leigh


You can simply use floats in the loop. $i++ in the final part of the loop means to increment the counter by 1. Simply change that to 0.45 and you are done.

for($i=0;$i<10;$i=$i + 0.45)
{
   echo $i;
}

// Edit

As many people have pointed out, there is inherent issue with floating point precision. The above example should work for small numbers $i < 100 but there may be issues when numbers become large.

like image 44
Kami Avatar answered Dec 26 '22 04:12

Kami