This code goes on a infinite loop开发者_如何学Python and gives me a
Fatal error: Maximum execution time of 30 seconds exceeded
This is the code i am using
<?php
$sofar = 1;
while ($sofar == 1);
{
echo $sofar;
$sofar == $sofar+1;
}
?>
Your problem is using two equal signs for the increment. Ie $sofar = $sofar + 1
is correct but you have $sofar ==
instead. Alternatively just $sofar++
or ++$sofar
works.
your basically doing
if($sofar == $sofar+1){/*Nothing*/}
so your expression would evaluate to
if(1 == 2){/*nothing*/}
There for $sofar never cahnges, you have to use =
to change or set the value of a variable.
your also adding a semi-colon at the end of your while
statement, The semicolon signifies the end of a PHP statement.
You should be doing
if( condition )
{
}
<?php
$sofar = 1;
while ($sofar == 1)
{
echo $sofar;
$sofar = $sofar+1;
}
?>
You have one = sign too many
And you have an ; after your while.
One = sign assign value Two == signs compare values
You could also use:
$sofar++;
$sofar += 1;
$sofar = $sofar +1;
Or perhaps:
$sofar = 1;
while ($sofar == 1)
{
echo ++$sofar;
}
Yes, definitely, it should be:
$sofar = $sofar + 1
rather than
$sofar == $sofar + 1
The latter one (which you are using) is a conditional statement.
Your using ==
which is not an assignment operator but a conditional operators.
you should be doing $sofar = $sofar+1;
or $sofar++;
to increment the value
==
is a comparison operator, not assigment operator (=
) so that instruction $sofar == $sofar+1;
actually doesn't do anything (it returns false
to nowhere).
In other words: $sofar
is always 1
.
You have a semicolon at the end of your while
statement. This is equivalent to
while ($sofar == 1) {
}
and will therefore result in an infinite loop. Also, you are doing a comparison, not an assignment. Your code should look like this:
<?php
$sofar = 1;
while ($sofar == 1)
{
echo $sofar;
$sofar = $sofar+1;
}
?>
<?php
$sofar = 1;
while ($sofar == 1) {
echo $sofar;
$sofar++;
}
?>
Increment with ++
.
精彩评论