Specifications
Each of these accepts a variable as input and returns the variable’s value converted to the
appropriate type.
Control Structures
Control structures are the structures within a language that allow us to control the flow of exe-
cution through a program or script. You can group them into conditionals (or branching) struc-
tures, and repetition structures, or loops. We will consider the specific implementations of each
of these in PHP next.
Making Decisions with Conditionals
If we want to sensibly respond to our user’s input, our code needs to be able to make decisions.
The constructs that tell our program to make decisions are called conditionals.
if Statements
We can use an if statement to make a decision. You should give the if statement a condition
to use. If the condition is true, the following block of code will be executed. Conditions in if
statements must be surrounded by brackets ().
For example, if we order no tires, no bottles of oil, and no spark plugs from Bob, it is probably
because we accidentally pressed the Submit button. Rather than telling us “Order processed,”
the page could give us a more useful message.
When the visitor orders no items, we might like to say, “You did not order anything on the pre-
vious page!” We can do this easily with the following if statement:
if( $totalqty == 0 )
echo “You did not order anything on the previous page!<br>”;
The condition we are using is $totalqty == 0. Remember that the equals operator (==)
behaves differently from the assignment operator (=).
The condition $totalqty == 0 will be true if $totalqty is equal to zero. If $totalqty is not
equal to zero, the condition will be false. When the condition is true, the echo statement will
be executed.
Code Blocks
Often we have more than one statement we want executed inside a conditional statement such
as if. There is no need to place a new if statement before each. Instead, we can group a num-
ber of statements together as a block. To declare a block, enclose it in curly braces:
if( $totalqty == 0 )
{
Using PHP
P
ART I
38
03 7842 CH01 3/6/01 3:39 PM Page 38