views:

374

answers:

6

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.

+36  A: 

Missing semi-colon after break


Its 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.

Its advisable to use braces to enclose the body of a conditional or a loop even if the body has 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.

codaddict
What the execution goose chase!
erisco
I actually didn't know that. +1
Cam
+2  A: 
for($a=0;$a<10;++$a)
{
       if($a==3) break;
       print $a;
}

@Downvoters: What's wrong aside from me being laconic?

Robus
not the down voter, but that else is redundant
Matt Ellen
+3  A: 

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, ' ';
}
judda
@Downvoters what was the problem with it ...
judda
Not the downvoter, but the OP's problem is he *does not* get a syntax error.
bmb
+12  A: 

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.

Octavian Damiean
A: 
for($a=0;$a<10;$a++) {
   if($a==3) { exit; }
   else { echo $a; }
}
Using `exit` is probably not the correct idea - sticking with `break` would have been better.
Jonathan Leffler
A: 

Use echo in place of print.

Why the downvotes ?