manishjangir
manishjangir

Reputation: 1695

For loop is not running for float values

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.

Upvotes: 8

Views: 3717

Answers (7)

Brijesh Gajjar
Brijesh Gajjar

Reputation: 562

<?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!

Upvotes: 1

Md. Maruf Hossain
Md. Maruf Hossain

Reputation: 922

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/>";
   }

?>

Upvotes: 2

Rok Kralj
Rok Kralj

Reputation: 48735

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>";
}

Upvotes: 0

Mob
Mob

Reputation: 11098

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

Upvotes: 4

Rok Kralj
Rok Kralj

Reputation: 48735

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>";
 }

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You could do:

<?php 

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

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

 ?>

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

Upvotes: 1

Distdev
Distdev

Reputation: 2312

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

I'd recommend to use integer indexes for loops

Upvotes: 3

Related Questions