05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

if<br />

The if statement checks the truthfulness of an expression and, if the expression is<br />

true, evaluates a statement. An if statement looks like:<br />

if (expression)<br />

statement<br />

To specify an alternative statement to execute when the expression is false, use the<br />

else keyword:<br />

if (expression)<br />

statement<br />

else<br />

statement<br />

For example:<br />

if ($user_validated)<br />

echo "Welcome!";<br />

else<br />

echo "Access Forbidden!";<br />

To include more than one statement in an if statement, use a block—a curly braceenclosed<br />

set of statements:<br />

if ($user_validated) {<br />

echo 'Welcome!";<br />

$greeted = 1;<br />

} else {<br />

echo "Access Forbidden!";<br />

exit;<br />

}<br />

<strong>PHP</strong> provides another syntax for blocks in tests and loops. Instead of enclosing the<br />

block of statements in curly braces, end the if line with a colon (:) and use a specific<br />

keyword to end the block (endif, in this case). For example:<br />

if ($user_validated) :<br />

echo "Welcome!";<br />

$greeted = 1;<br />

else :<br />

echo "Access Forbidden!";<br />

exit;<br />

endif;<br />

Other statements described in this chapter also have similar alternate style syntax<br />

(and ending keywords); they can be useful if you have large blocks of HTML inside<br />

your statements. For example:<br />

<br />

<br />

<br />

First Name:Sophia<br />

<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Flow-Control Statements | 47

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

Saved successfully!

Ooh no, something went wrong!