Home » Php » php – For loop is not running for float values

php – For loop is not running for float values

Posted by: admin July 12, 2020 Leave a comment

Questions:

i have a for loop like below

<?php 

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

 echo $i."<br>";
 }

 ?>

this code prints the value of i till 9.6 not 10.

why it returns the value of i=10 at last.

How to&Answers:

because of representing of float numbers for machines – http://en.wikipedia.org/wiki/Floating_point

I’d recommend to use integer indexes for loops

Answer:

Use += to increment it, instead of just plus. As it is now, its an infinite loop for me.

Edit: For some reason PHP doesn’t work properly with different types in loops.

This below should work

for($i=0;$i<=100;$i+=4){
   echo $i/10."<br>";
 }

Here’s the var_dump

int(0)

float(0.4)

float(0.8)

float(1.2)

float(1.6)

int(2)

float(2.4)

float(2.8)

float(3.2)

float(3.6)

int(4)

float(4.4)

float(4.8)

float(5.2)

float(5.6)

int(6)

float(6.4)

float(6.8)

float(7.2)

float(7.6)

int(8)

float(8.4)

float(8.8)

float(9.2)

float(9.6)

int(10)

That’s probably the auto-casting PHP is doing that is causing this

Answer:

There is a problem with accurate FLOAT comparison (which takes place in <=).

Do it like this:

 for($i=0; $i<=100; $i+=4){
     echo ($i/10)."<br>";
 }

Answer:

For exact comparison you can round those value , As like following …

<?php

   for($i=0; round($i,1) <= 10; $i += 0.4){
      echo $i."<br/>";
   }

?>

Answer:

You could do:

<?php 

 for($i=0;$i<=100;$i += 4){

 echo ($i/10)."<br>";
 }

 ?>

result here: http://codepad.org/CxvzEUeq

Answer:

<?php

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

echo $i."<br>";

}

?>

if u put i<=10 then it will continue printing to value 10 but if remove = sign then it will stop at 9!

Answer:

When comparing, you have to use the epsilon value, which denotes the allowed mistake when comparing float values.

$epsilon=0.000001; //a very small number

for($i=0; $i<10 or abs($i-10)<$epsilon; $i+=0.4){
   echo $i."<br>";
}