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?
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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With