Page 90 - Beginning PHP 5.3
P. 90
Part II: Learning the Language
Making Decisions
Like most programming languages, PHP lets you write code that can make decisions based on the result
of an expression. This allows you to do things like test if a variable matches a particular value, or if a
string of text is of a certain length. In essence, if you can create a test in the form of an expression that
evaluates to either true or false , you can use that test to make decisions in your code.
You studied expressions in Chapter 3 , but you might like to quickly review the “ Operators and
Expressions ” section in that chapter to give yourself an idea of the kinds of expressions you can create.
You can see that, thanks to the wide range of operators available in PHP, you can construct some pretty
complex expressions. This means that you can use almost any test as the basis for decision - making in
your code.
PHP gives you a number of statements that you can use to make decisions:
❑ The if statement
❑ The else and elseif statements
❑ The switch statement
You explore each of these statements in the coming sections.
Simple Decisions with the if Statement
The easiest decision - making statement to understand is the if statement. The basic form of an if
construct is as follows:
if ( expression ) {
// Run this code
}
// More code here
If the expression inside the parentheses evaluates to true , the code between the braces is run. If the
expression evaluates to false , the code between the braces is skipped. That ’ s really all there is to it.
It ’ s worth pointing out that any code following the closing brace is always run, regardless of the result of
the test. So in the preceding example, if expression evaluates to true , both the Run this code and More
code here lines are executed; if expression evaluates to false , Run this code is skipped but
More code here is still run.
Here ’ s a simple real - world example:
$widgets = 23;
if ( $widgets == 23 ) {
echo “We have exactly 23 widgets in stock!”;
}
52
9/21/09 8:52:06 AM
c04.indd 52
c04.indd 52 9/21/09 8:52:06 AM