While loop problem

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

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

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: 1803
Joined: Thu Mar 10, 2011 5:07 pm

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)

Post Reply
  • Information
  • Who is online

    Users browsing this forum: No registered users and 7 guests