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.

Last Name:Lee<br />

<br />

<br />

<br />

Please log in.<br />

<br />

Because if is a statement, you can chain them:<br />

if ($good)<br />

print('Dandy!');<br />

else<br />

if ($error)<br />

print('Oh, no!');<br />

else<br />

print("I'm ambivalent...");<br />

Such chains of if statements are common enough that <strong>PHP</strong> provides an easier syntax:<br />

the elseif statement. For example, the previous code can be rewritten as:<br />

if ($good)<br />

print('Dandy!');<br />

elseif ($error)<br />

print('Oh, no!');<br />

else<br />

print("I'm ambivalent...");<br />

The ternary conditional operator (?:) can be used to shorten simple true/false tests.<br />

Take a common situation such as checking to see if a given variable is true and printing<br />

something if it is. With a normal if/else statement, it looks like this:<br />

<br />

With the ternary conditional operator, it looks like this:<br />

<br />

Compare the syntax of the two:<br />

if (expression) true_statement else false_statement<br />

(expression) ? true_expression : false_expression<br />

The main difference here is that the conditional operator is not a statement at all.<br />

This means that it is used on expressions, and the result of a complete ternary<br />

expression is itself an expression. In the previous example, the echo statement is<br />

inside the if condition, while when used with the ternary operator, it precedes the<br />

expression.<br />

switch<br />

It often is the case that the value of a single variable may determine one of a number<br />

of different choices (e.g., the variable holds the username and you want to do<br />

something different for each user). The switch statement is designed for just this<br />

situation.<br />

48 | 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!