Chapter 4. Control Structures
In This Chapter
Getting familiar with
if-else
conditionalsUsing
switch
structuresWorking with
while
andfor
loopsUsing comparison operators
Control structures allow you to make decisions or control the order of execution of your program. if-else
conditionals, case
statements, for
loops, and while
loops are all control structures.
Introducing if-else Conditionals
If you have two or more courses of action to choose from in your program, a perfect way to handle this is through if-else
conditionals.
if conditionals
The simplest form of a control statement is the if
conditional, also known as an if
statement or an if
construct.
An if
conditional evaluates an expression down to its True
or False
value. If the value is equal to True
, some code will be executed. If the value is False
, the code won't be executed.
Here's how you construct an if
conditional:
Start with
if
.Follow this with a condition expression in parentheses,
()
.Follow this with the code to be executed if the expression is met.
This code must be surrounded by curly braces.
The simplest form of an if
conditional uses a variable that you expect to contain the value True
or False
(known as a Boolean variable) as the expression to be evaluated by the if
statement:
$expression = true; if($expression){ print "true!"; }
This code would print true!
.
If you wanted to check $expression
to see if it was equal to False
, you could precede it with an exclamation point:
$expression = true; if(!$expression){ print "false!"; ...
Get HTML, XHTML, and CSS All-In-One Desk Reference For Dummies® now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.