Simple for loop not working [closed]
I've just started learning programming. I'm studying for loops but
this program does not work as expected. I want to break the loop when
$a
is equal to 3
so that I get the output 1 2
but I get 3
as output :(
for($a=0;$a<开发者_StackOverflow中文版10;++$a)
{
if($a==3)
break
print"$a ";
}
Please help.
Missing semi-colon after break
It's rather interesting to know why your program behaves the way it does.
The general syntax of break
in PHP is:
break Expression;
The expression is optional, but if present its value tells how many nested enclosing structures are to be broken out of.
break 0;
and break 1;
are same as break;
Your code is equivalent to
if($a==3)
break print"$a ";
Now the print
function in PHP always return 1
. Hence it is equivalent to
if($a==3)
break 1;
so when $a
is 3
you print its value and break.
It's advisable to use braces to enclose the body of a conditional or a loop even if the body has a single statement. In this case enclosing the if
body in braces:
if($a==3) {
break
}
print"$a ";
would have given a syntax error: PHP expects a ;
but finds a }
All of the above applies to the PHP continue
as well. So the program
for($a=0;$a<10;++$a)
{
if($a==3)
continue
print"$a ";
}
also prints 3
for a similar reason.
You are missing a semicolon at the end of break. ;)
And even with the semicolon it will not work as you'd expect it to since it will count from 0
to 2
. You have to write it like this to get only 1 2
.
<?php
for($a=1;$a<10;++$a)
{
if($a==3)
break;
print"$a ";
}
?>
Note $a is now one in the for loop initialization.
EDIT: Another thing I've noticed which you should be aware of. In your for loop control you have a pre-increment (++$a
). That basically means that PHP increments the value of $a
and then returns $a
. Another option is the post-increment ($a++
) where $a
gets returned and then gets incremented by one.
In your case both ways will get you the correct output tho.
This sometimes is pretty important. Just keep that in mind.
As codaddict said, you are missing the semi-colon after break.
Your code should look like:
for($a=0;$a<10;++$a)
{
if($a==3)
break;
echo $a, ' ';
}
for($a=0;$a<10;++$a)
{
if($a==3) break;
print $a;
}
@Downvoters: What's wrong aside from me being laconic?
for($a=0;$a<10;$a++) {
if($a==3) { exit; }
else { echo $a; }
}
Use echo
in place of print
.
精彩评论