05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

You can use break and continue statements in a do/while statement just as in a normal<br />

while statement.<br />

The do/while statement is sometimes used to break out of a block of code when an<br />

error condition occurs. For example:<br />

do {<br />

// do some stuff<br />

if ($error_condition)<br />

break;<br />

// do some other stuff<br />

} while (false);<br />

Because the condition for the loop is false, the loop is executed only once, regardless<br />

of what happens inside the loop. However, if an error occurs, the code after the<br />

break is not evaluated.<br />

for<br />

The for statement is similar to the while statement, except it adds counter initialization<br />

and counter manipulation expressions, and is often shorter and easier to read<br />

than the equivalent while loop.<br />

Here’s a while loop that counts from 0 to 9, printing each number:<br />

$counter = 0;<br />

while ($counter < 10) {<br />

echo "Counter is $counter\n";<br />

$counter++;<br />

}<br />

Here’s the corresponding, more concise for loop:<br />

for ($counter = 0; $counter < 10; $counter++)<br />

echo "Counter is $counter\n";<br />

The structure of a for statement is:<br />

for (start; condition; increment)<br />

statement<br />

The expression start is evaluated once, at the beginning of the for statement. Each<br />

time through the loop, the expression condition is tested. If it is true, the body of the<br />

loop is executed; if it is false, the loop ends. The expression increment is evaluated<br />

after the loop body runs.<br />

The alternative syntax of a for statement is:<br />

for (expr1; expr2; expr3):<br />

statement;<br />

...;<br />

endfor;<br />

52 | Chapter 2: Language Basics<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!