While loop problem

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

sohrabkln
New php-forum User
New php-forum User
Posts: 2
Joined: Wed Oct 03, 2012 9:54 am

While loop problem

Postby sohrabkln » Wed Oct 03, 2012 10:02 am

<?php
$i=0;
$j=5;
while($j==5)
{echo $i;
echo ",";
$i=$i+.2;
if($i==1)
{break;}
?>
output: 0,.2,.4,.8
but why
<?php
$i=0;
$j=5;
while($j==5)
{echo $i;
echo ",";
$i=$i+.2;
if($i==2)
{break;}
?>

no output?

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: While loop problem

Postby seandisanti » Wed Oct 03, 2012 10:47 am

it's a bug, probably a rounding error. kind of cool, but avoidable. First, the loops should be written as

Code: Select all

while ($i < x){}

where x is the 1 or 2.

It is actually generating output but going into an infinite loop because it doesn't exit correctly when $i is greater than 1.4 with your example. For demonstration purposes, i've modified your code slightly. code blocks are now closed and i added a second exit condition for the second while loop so that it will exit every time, but you can still see that the break is not executed when it should be.

Code: Select all

<?php
   $i=0;
   $j=5;
   while($j==5)
   {
      echo $i;
      echo ",";
      $i=$i+.2;
      if($i==1)
      {
         break;
      }
   }
?>

<?php
   $i=0;
   $j=5;
   while($j==5 && $i <3)
   {
      echo $i;
      echo ",";
      $i=$i+0.2;
      if($i==2) //even though $i hits 2 it doesn't exit
      {
         break;
      }
   }
?>
Last edited by seandisanti on Thu Oct 04, 2012 9:51 am, edited 1 time in total.

johnj
php-forum Super User
php-forum Super User
Posts: 1805
Joined: Thu Mar 10, 2011 5:07 pm

Re: While loop problem

Postby johnj » Wed Oct 03, 2012 9:46 pm

if you want to numerically compare then it is better to use the bcmath library. in this case it should be:

Code: Select all

if(bccomp($i,2) == false)


Return to “PHP coding => General”

Who is online

Users browsing this forum: Google Feedfetcher and 2 guests

cron