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<10;++$a)
{
if($a==3)
break
print"$a ";
}
Please help.
Answer 530f606f548c35ffb900591f Remove the semicolon at the end of the first line. Then it will loop from 100 to 5. In case you want to end on zero then it should be i >=0; but I think you want it to stop at 5 which it is fine the way you have it.
The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10.
Tips. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.
Yes it is perfectly correct to do so.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With