O'Reilly logo

Learning PHP & MySQL, 2nd Edition by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. PHP Decision-Making

In the last chapter you started to get a feel for programming with PHP and some code basics. Now it's time to expand your comfort, knowledge, and ability with PHP. We'll start with expressions and statements.

Expressions

There are several building blocks of coding that you need to understand: statements, expressions, and operators. A statement is code that performs a task. Statements are made up of expressions and operators. An expression is a piece of code that evaluates to a value. A value can be a number, a string of text, or a Boolean.

Tip

A Boolean is an expression that results in a value of either TRUE or FALSE. For example, the expression 10 > 5 (10 is greater than 5) is a Boolean expression because the result is TRUE. All expressions that contain relational operators, such as the less-than sign (<), are Boolean. Some of the Boolean operators are AND, OR, and NOT. Boolean operators will be discussed at greater length later in this chapter.

An operator is a code element that acts on an expression in some way. For instance, a minus sign (-) can be used to tell the computer to decrement the value of the expression after it from the expression before it. For example:

$account_balance=$credits-$debits;

The most important thing to understand about expressions is how to combine them into compound expressions and statements using operators. So, we're going to look at operators used to turn expressions into more complex expressions and statements.

The simplest form of expression is a literal or a variable. A literal evaluates to itself. Some examples of literals are numbers, strings, and constants. A variable evaluates to the value assigned to it. For instance, any of the expressions in Table 4-1 are valid.

Table 4-1. Valid expressions

Example

Type

1

A numeric value literal

"Becker Furniture"

A string literal

TRUE

A constant literal

$user_name

A variable with username as a string, but it doesn't necessarily have to be a string

1+1

A numeric value expression that evaluates to a literal

Although a literal or variable may be a valid expression, they don't do anything. You get expressions to do things such as math or assignment by linking them together with operators.

An operator combines simple expressions into more complex expressions by creating relationships between simple expressions that can be evaluated. For instance, if the relation you want to establish is the cumulative joining of two numeric values together, you could write 3 + 4.

Figure 4-1 shows how the parts of an expression come together.

Operands and operators working together as an expression to form a value

Figure 4-1. Operands and operators working together as an expression to form a value

The numbers 3 and 4 are each valid expressions. Adding 3 + 4 is also a valid expression, whose value, in this case, happens to be 7. The plus sign (+) is an operator. The numbers to either side of it are its arguments, or operands. An argument or operand is something on which an operator takes action; for example, an argument or operand could be a directive from your housemate to empty the dishwasher, and the operator empties the dishwasher. Different operators have different types and numbers of operands. Operators can also be overloaded, which means that they do different things in different contexts.

You've probably guessed from this information that two or more expressions connected by operators are called an expression. You're right, as operators create complex expressions. The more subexpressions and operators you have, the longer and more complex the expression. But no matter what, as long as it can be resolved to a value, it's still an expression.

When expressions and operators are assembled to produce a piece of code that actually does something, you have a statement. We discussed statements in Chapter 3. They end in semicolons (;), which is the programming equivalent of ending a complete sentence with a period.

For instance, $Margaritaville + $Sun_Tan_Application is an expression. It results in the sum of the values of $Margaritaville + $Sun_Tan_Application, but it doesn't do anything. While it's an expression, the output doesn't make any sense, but if you add the equals sign (=), $Fun_in_the_Sun = $Margaritaville + $Sun_Tan_Application;, you get a statement because the expression does something. As Example 4-1 demonstrates, it assigns the sum of the values of $Margaritaville + $Sun_Tan_Application to $Fun_in_the_Sun.

Example 4-1. Sum of values

<?php
$Margaritaville = 3; // Three margaritas
$Sun_Tan_Application = 2; // Two applications of sun tan
$Fun_in_the_Sun = $Margaritaville + $Sun_Tan_Application;
echo $Fun_in_the_Sun;
?>

Example 4-1 outputs:

5

There really isn't much more to understand about expressions except for how to assemble them into compound expressions and statements using operators. Next, we're going to discuss operators that are used to turn expressions into more complex expressions and statements.

Operator Concepts

PHP has many types of operators, including:

  • Arithmetic operators

  • Array operators

  • Assignment operators

  • Bitwise operators

  • Comparison operators

  • Execution operators

  • Incrementing/decrementing operators

  • Logical operators

  • String operators

The operators are listed as found on http://www.php.net/manual/en/language.operators.php. There are some operators we're not going to discuss so you can get up and running with PHP as quickly as possible. These include some of the casting operators that we'll just skim the surface of for now. Each operator has four critical properties in addition to its core functionality:

  • Number of operands

  • Type of operands

  • Order of precedence

  • Operator associativity

The easiest place to start is by talking about the operands.

Number of Operands

Different operands take different numbers of operands. Many operators are used to combine two expressions into a more complex single expression; these are called binary operators. Binary operators include addition, subtraction, multiplication, and division.

Other operators take only one operand; these are called unary operators. Think of the negation operator (-) that multiplies a numeric value by −1. The preincrement and predecrement operators described in Chapter 3 are also unary operators.

A ternary operator takes three operands. The shorthand for an if statement, which we'll talk about later when discussing conditionals, takes three operands.

Types of Operands

You need to be mindful of the type of operand on which an operator is meant to work because certain operators expect their operands to be of particular data types. PHP attempts to make your life as easy as possible by automatically converting operands to the data type that an operator is expecting. There are times, however, that an automatic conversion isn't possible.

Mathematical operators are an example of where you need to be careful with your types. They take only numbers as operands. For example, when you try to multiply two strings, PHP can convert the strings to numbers. While "Becker" * "Furniture" is not a valid expression, it returns zero. On the other hand, an expression that is converted without an error is "70" * "80". This evaluates to 5600. Although 70 and 80 are strings, PHP is able to convert them to the number type required by the mathematical operator.

There will be times when you want to explicitly set or convert a variable's type. There are two ways to do this in PHP: first, by using settype to actually change the data type; or second, by casting, which temporarily converts the value. PHP uses casting to convert data types. When PHP does the casting for you automatically, it's called implicit casting. You can also specify data types explicitly, but it's not something that you'll likely need to do.

Tip

PHP uses implicit casting to cast to the type that the operator requires.

The cast types allowed are:

(int), (integer)

Cast to integer, whole numbers without a decimal part.

(bool), (boolean)

Cast to Boolean.

(float), (double), (real)

Cast to float, numbers that may include a decimal part.

(string)

Cast to string.

(array)

Cast to array.

(object)

Cast to object.

To use a cast, place it before the variable to cast, as shown in Example 4-2. The $test_string variable contains the string 1234.

Example 4-2. Casting a variable

$test=1234;
$test_string = (string)$test;

Keep in mind that it may not always be obvious what will happen when casting between certain types. You might run into problems if you don't watch yourself when manipulating variable types.

Some binary operators, such as the assignment operators, have further restrictions on the lefthand operand. Because the assignment operator is assigning a value to the lefthand operator, it must be something that can take a value, such as a variable. Example 4-3 demonstrates good and bad lefthand expressions.

Example 4-3. Lefthand expressions

3 = $locations; // bad - a value cannot be assigned to the literal 3
$a + $b = $c; //bad - the expression on the left isn't one variable
$c = $a + $b; //OK
$stores = "Becker"." "."Furniture"; // OK

Tip

There is a simpler way to remember this. The lefthand expression in assignment operations is known as an L-value. L-values in PHP are variables, elements of an array, and object properties. Don't worry about object properties.

Order of precedence

The order of precedence of an operator determines which operator processes first in an expression. For instance, the multiplication and division process before addition and subtraction. You can see a simplified table at http://www.zend.com/manual/language.operators.php#language.operators.precedence.

If the operators have the same precedence, they are processed in the order they appear in the expression. For example, multiplication and division process in the order in which they appear in an expression because they have the same precedence. Operators with the same precedence can occur in any order without affecting the result.

Most expressions don't have more than one operator of the same precedence level, or the order in which they process doesn't change the result. As shown in Example 4-4, when adding and subtracting the following sequence of numbers, it doesn't matter whether you add or subtract first—the result is still 1.

Example 4-4. Order of precedence

2 + 4 - 5 == 1;
4 - 5 + 2 == 1;

4 * 5 / 2 == 10;
5 / 2 * 4 == 10;

2 + 4 - 5 == 1;
4 - 5 + 2 == 1;

When using expressions that contain operators of different precedence levels, the order can change the value of the expression. You can use parentheses, ( and ), to override the precedence levels or just to make the expression easier to read. Example 4-5 shows how to change the default precedence.

Example 4-5. Changing the default precedence using parentheses

echo 2 * 3 + 4 + 1;
echo 2 * (3 + 4 + 1);

This outputs:

11
16

In the second expression, the multiplication is done last because of the parentheses overriding the default order.

PHP has several levels of precedence, enough that it's difficult to keep track of them without checking a reference. Table 4-2 is a list of PHP operators sorted by order of precedence from highest to lowest. Operators with the same level number are all of the same precedence.

Tip

The Association column lists operators that are right-to-left instead of left-to-right. We'll discuss associativity next.

Table 4-2. List of PHP operators

Operator

Description

Operands

Association

Level

NEW

Create new object

Constructor call

Right to left

1

.

Property access (dot notation)

Objects

 

2

[ ]

Array index

Array, integer, or string

 

2

( )

Function call

Function or argument

 

2

!

Logical NOT

Unary

Right to left

3

~

Bitwise NOT

Unary

Right to left

3

++, --

Increment and decrement operators

1value

Right to left

3

+, -

Unary plus, negation

Number

Right to left

3

(int)

Cast operators

Unary

Right to left

3

(double)

Cast operators

Unary

Right to left

3

(string)

Cast operators

Unary

Right to left

3

(array)

Cast operators

Unary

Right to left

3

(object)

Cast operators

Unary

Right to left

3

@

Inhibit errors

Unary

Right to left

3

*, /, %

Multiplication, division

Numbers

 

4

+, -

Addition, subtraction

Numbers

 

5

.

Concatenation

Strings

 

5

<<, >>

Bitwise shift left, bitwise shift right

Binary

 

6

<, <=, >, >=

Comparison operators

Numbers, strings

 

7

==, !=

Equality, inequality

Any

 

8

===, !==

Identity, nonidentity

Any

 

8

&

Bitwise AND

Binary

 

9

^

Bitwise NOR

Binary

 

10

|

Bitwise OR

Binary

 

11

&&

Logical AND

Boolean

 

12

||

Logical OR

Boolean

 

13

? :

Conditional

Boolean

Right to left

14

=

Assignment

1value=any

Right to left

15

AND

Logical AND

Boolean

 

16

OR

Logical OR

Boolean

 

17

XOR

Logical XOR

Boolean

 

18

Associativity

All operators process their operators in a certain direction. This direction is called associativity, and it depends on the type of operator. Most operators are processed from left to right, which is called left associativity. For example, in the expression 3 + 5 - 2, 3 and 5 are added together, and then 2 is subtracted from the result, evaluating to 8. While left associativity means that the expression is evaluated from left to right, right associativity means the opposite.

Since the assignment operator has right associativity, it is one of the exceptions because right associativity is less common. The expression $a=$b=$c processes by $b being assigned the value of $c, and then $a being assigned the value of $b. This assigns the same value to all of the variables. If the assignment operator is right associative, the variables might not have the same value.

If you're thinking that this is incredibly complicated, don't worry. These rules are enforced only if you fail to be explicit about your instructions. Keep in mind that you should always use brackets in your expressions to make your actual meaning clearer. This helps both PHP and also other people who may need to read your code.

Tip

If you accidentally use & instead of &&, or | instead of ||, you'll end up getting the wrong operator. & and | compare binary data bit by bit. PHP will convert your operands into binary data and apply binary operators.

Relational Operators

In Chapter 3 we discussed assignment and math operators. Relational operators provide the ability to compare two operands and return either TRUE or FALSE regarding the comparison. An expression that returns only TRUE or FALSE is called a Boolean expression, which we discussed in the previous chapter. These comparisons include tests for equality and less than or greater than. These comparison operators allow you to tell PHP when to do something based on whether a comparison is true so that decisions can be made in your code.

Equality

The equality operator, a double equals sign (==), is used frequently. Using the single equals sign (=) in its place is a common logical error in programs, since it assigns values instead of testing equality.

If the two operands are equal, TRUE is returned; otherwise, FALSE is returned. If you're echoing your results, TRUE is printed as 1 in your browser. FALSE is 0 and won't display in your browser.

It's a simple construct, but it also allows you to test for conditions. If the operands are of different types, PHP attempts to convert them before comparing.

For example, '1' == 1 is true. Also, $a == 1 is true if the variable $a is assigned to 1.

If you don't want the equality operator to automatically convert types, you can use the identity operator, a triple equals sign (===), which checks whether the values and types are the same. For example, '1' === 1 is false because they're different types, since a string doesn't equal an integer.

Sometimes you might want to check to see whether two things are different. The inequality operator, an exclamation mark before the equals sign (!=), checks for the opposite of equality, which means that it is not equal to anything; therefore, it's FALSE.

'1' != 'A'    // true
'1' != '1'    // false

Comparison operators

You may need to check for more than just equality. Comparison operators test the relationship between two values. You may be familiar with these from high school math. They include less than (<), less-than or equal to (<=), greater than (>), and greater-than or equal to (>=).

For example, 3<4 is TRUE, while 3<3 is FALSE, and 3<=3 is TRUE.

Comparison operators are often used to check for something happening up until a set point. For example, an online store might offer free shipping if you purchase five or more items. So, the code must compare the number of items to the number five before changing the shipping cost.

Logical operators

Logical operators work with the Boolean results of relational operators to build more complex logical expressions; there are four logical operators shown in Table 4-3. These operators are also Boolean operators.

Table 4-3. Logical operators

Logical operator

Meaning

AND

TRUE if both operands must be TRUE

OR

TRUE if at least one operand is TRUE

XOR

TRUE if only one operand is TRUE

NOT

TRUE if FALSE, FALSE if TRUE

Tip

Because they have different precedence levels, both AND and OR have two representations. AND can be given a higher precedence level as &&, while OR can be given a higher precedence level as ||.

To test whether both operands are true, use the AND operator, also represented as the double ampersands (&&) seen in Table 4-2. Both the double ampersand as well as AND are logical operators; the only difference is that the double ampersand is evaluated before the AND operator. The operators || and OR follow the same rule. TRUE is returned only if both operands are TRUE; otherwise, FALSE is returned. See Table 4-3 for more information.

To test whether one operand is TRUE, use the OR operator, which is also represented as double vertical bars or pipes (||). TRUE is returned only if either or both operands are TRUE.

Tip

Using the OR operator can create tricky program logic problems. If PHP finds that the first operand is TRUE, it won't evaluate the second operand. While this saves execution time, you need to be careful that the second operator doesn't contain code that needs to be executed for your program to work properly.

To test whether only one operand is TRUE, use XOR. XOR returns TRUE if one and only one operand is TRUE. It returns FALSE if both operands are TRUE.

To negate a Boolean value, use the NOT operator, represented as an exclamation point (!). It returns TRUE if the operand has a value of FALSE. It returns FALSE if the operand is TRUE.

Table 4-4 displays logical statements and their results.

Table 4-4. Logical statements and their results

Example logical statement

Result

TRUE AND TRUE

TRUE

FALSE AND TRUE

FALSE

TRUE OR FALSE

TRUE

FALSE OR FALSE

FALSE

TRUE XOR TRUE

FALSE

TRUE XOR FALSE

TRUE

!TRUE

FALSE

!FALSE

TRUE

Conditionals

Conditionals, like variables, form a building block in our foundation of PHP development. They alter a script's behavior according to the criteria set in the code. There are three primary conditionals in PHP:

  • if

  • ? : : (shorthand for an if statement)

  • switch

The switch statement is useful when you have multiple things you want to do and need to take different actions based on the contents of a variable. The switch statement is discussed in more detail later in this chapter.

The if Statement

The if statement offers the ability to execute a block of code if the supplied condition is TRUE; otherwise, the code block doesn't execute. The condition can be any expression, including tests for nonzero, null, equality, variables, and returned values from functions.

No matter what, every single conditional you create includes a conditional clause. If a condition is TRUE, the code block in curly braces ({}) is executed. If not, PHP ignores it and moves to the second condition, continuing through all clauses written until PHP hits an else. Then it automatically executes that block only if the IF condition proves to be FALSE; otherwise, it moves on. The curly braces are not required if you have only one line of code to execute in the block. An else statement is not always required.

Figure 4-2 demonstrates how an if statement works. The else block always needs to come last and be treated as if it's the default action. This is similar to the semicolon (;). Common true conditions are:

  • $var, if $var has a value other than the empty set (0), an empty string, or NULL

  • isset ($var), if $var has any value other than NULL, including the empty set or an empty string

  • TRUE or any variation thereof

    Execution branching based on an expression

    Figure 4-2. Execution branching based on an expression

We haven't talked yet about the second bullet point. isset( ) is a function that checks whether a variable is set. A set variable has a value other than NULL. Table 4-2 shows comparative and logical operators, which can be used in conjunction with parentheses ( ) to create more complicated expressions.

The syntax for the if statement is:

if (conditional expression){
    block of code;
}

If the expression in the conditional block evaluates to TRUE, the block of code that follows it executes. In this example, if the variable $username is set to 'Admin', a welcome message is printed. Otherwise, nothing happens.

if ($username == "Admin") {
    echo ('Welcome to the admin page.');
}

The curly braces aren't needed if you want to execute only one statement, but it's good practice to always use them, as it makes the code easier to read and more resilient to change.

The else statement

The optional else statement (see Example 4-6) provides a default block of code that executes if the condition returned is FALSE. else cannot be used without an if statement, as it doesn't take a conditional itself. So, else and if have to always be together in your code.

Example 4-6. else and if statements

if ($username == "Admin"){
    echo ('Welcome to the admin page.');
}
else {
    echo ('Welcome to the user page.');
}

Remember to close out the code block from the if conditional when you've used braces to start your block of code. Similar to the if block, the else block should also use curly braces to begin and end the code.

The elseif statement

All of this is great except for when you want to test for several conditions simultaneously. To do this, you can use the elseif statement. It allows for testing of additional conditions until one is found to be true or until you hit the else block. Each elseif has its own code block that comes directly after the elseif condition. The elseif must come after the if statement and before an else statement if one exists.

The elseif structure is a little complicated, but Example 4-7 should help you understand it.

Example 4-7. Checking multiple conditions

if ($username == "Admin"){
    echo ('Welcome to the admin page.');
}
elseif ($username == "Guest"){
    echo ('Please take a look around.');
}
else {
    echo ("Welcome back, $username.");
}

Here you can check for two conditions and take different actions based on each of the values for $username. Then you also have the option to do something else if the $username isn't one of the first two.

The next construct builds on the concepts of the if/else statement, but it allows you to efficiently check the results of an expression to many values without having a separate if/else for each value.

The ? Operator

The ? operator is a ternary operator, which means it takes three operands. It works like an if statement but returns a value from one of the two expressions. The conditional expression determines the value of the expression. A colon (:) is used to separate the expressions, as shown here:

{expression} ? return_when_expression_true : return_when_expression_false;

Example 4-8 tests a value and returns a different string based on whether it's TRUE or FALSE.

Example 4-8. Using the ? operator to create a message

<?php
$logged_in = TRUE;
$user = "Admin";
$banner = ($logged_in==TRUE)?"Welcome back, $user!":"Please login.";

echo "$banner";
?>

Example 4-8 produces:

Welcome back, Admin!

This can be pretty useful for checking errors. Now, let's look at a statement that lets you check an expression against a list of possible values to pick the executable code.

The switch Statement

The switch statement compares an expression to numerous values. It's very common to have an expression, such as a variable, for which you'll want to execute different code for each value stored in the variable. For example, you might have a variable called $action, which may have the values add, modify, and delete. The switch statement makes it easy to define a block of code to execute in response to each of those values.

To illustrate the difference between using the if statement and the switch statement to test a variable for several values, we'll show you the code for the if statement (in Example 4-9), and then for the switch statement (in Example 4-10).

Example 4-9. Using if to test for multiple values

if ($action == "ADD") {
    echo "Perform actions for adding.";
    echo "As many statements as you like can be in each block.";
}
elseif ($action == "MODIFY") {
    echo "Perform actions for modifying.";
}
elseif ($action == "DELETE") {
    echo "Perform actions for deleting.";
}

Example 4-10. Using switch to test for multiple values

switch ($action) {
    case "ADD":
        echo "Perform actions for adding.";
        echo "As many statements as you like can be in each block.";
        break;
    case "MODIFY":
        echo "Perform actions for modifying.";
        break;
    case "DELETE":
        echo "Perform actions for deleting.";
        break;
}

The switch statement works by taking the value after the switch keyword and comparing it to the cases in the order in which they appear. If no case matches, the code isn't executed. Once a case matches, the code is executed. The code in subsequent cases also executes until the end of the switch statement or until a break keyword. This is useful for processes that have several sequential steps. If the user has already done some of the steps, he can jump into the process where he left off.

Tip

The expression after the switch statement must evaluate to a simple type, such as a number, an integer, or a string. An array can be used only if a specific member of the array is referenced as a simple type.

There are numerous ways to tell PHP not to execute cases besides the matching case.

Breaking out

If you want only the code in the matching block to execute, place a break keyword at the end of that block. When PHP comes across the break keyword, processing jumps to the next line after the entire switch statement. Example 4-11 illustrates how processing works with no break statements.

Example 4-11. What happens when there are no break keywords

$action = "ASSEMBLE ORDER";
switch ($action) {
    case "ASSEMBLE ORDER":
        echo "Perform actions for order assembly.<br />";
    case "PACKAGE":
        echo "Perform actions for packing.<br />";
    case "SHIP":
        echo "Perform actions for shipping.<br />";
    }

If the value of $action is "ASSEMBLE ORDER", the result is:

Perform actions for order assembly.
Perform actions for packing.
Perform actions for shipping.

However, if a user has already assembled an order, a value of "PACKAGE" produces the following:

Perform actions for packing.
Perform actions for shipping.

Defaulting

The SWITCH statement also provides a way to do something if none of the other cases matches, which is similar to the else statement in an if, elseif, or else block.

Use the DEFAULT: statement for the SWITCH's last case statement (see Example 4-12).

Example 4-12. Using the DEFAULT: statement to generate an error

switch ($action) {
    case "ADD":
        echo "Perform actions for adding.";
        break;

    case "MODIFY":
        echo "Perform actions for modifying.";
        break;
    case "DELETE":
        echo "Perform actions for deleting.";
        break;
    default:
        echo "Error: Action must be either ADD, MODIFY, or DELETE.";
}

The switch statement also supports the alternate syntax in which the switch and endswitch keywords define the start and end of the switch instead of the curly braces {}, as shown in Example 4-13.

Example 4-13. Using endswitch to end the switch definition

switch ($action):
    case "ADD":
       echo "Perform actions for adding.";
       break;
    case "MODIFY":
       echo "Perform actions for modifying.";
       break;
    case "DELETE":
       echo "Perform actions for deleting.";
       break;
    default:
       echo "Error: Action must be either ADD, MODIFY, or DELETE.";
endswitch;

You've learned that you can have your programs execute different code based on conditions called expressions. The switch statement provides a convenient format for checking the value of an expression against numerous possible values.

Looping

Now that you've changed the flow of your PHP program based on comparisons, you need to learn that if you want to repeat a task until a comparison is FALSE, you'll need to use looping. Each time the code in the loop executes, it is called an iteration. This is useful for many common tasks, such as displaying the results of a query by looping through the returned rows. PHP provides the while, for, and do ... while constructs to perform loops.

Each of the loop constructs requires two basic pieces of information. First, the condition to stop looping is defined just like the comparison in an if statement. Second, the code to perform is also required and specified either on a single line or within curly braces. A logical error would be to omit the code from a loop that relies on the code executed to cause the loop to stop, causing an infinite loop.

The code is executed as long as the expression evaluates to TRUE. To avoid an infinite loop, which would loop forever, your code should have the expressions eventually become FALSE. When this happens, the loop stops, and execution continues with the next line of code, following the logical loop.

while Loops

The while loop takes the expression followed by the code to execute. Figure 4-3 illustrates how a while loop processes.

How a while loop executes

Figure 4-3. How a while loop executes

The syntax for a while loop is:

while (expression)
{
  code to  execute;
}

An example is shown in Example 4-14.

Example 4-14. A sample while loop that counts to 10

<?php
$num = 1;

while ($num <= 10){
    print "Number is $num<br />";
    $num++;
}

print 'Done.';
?>

Example 4-14 produces the following:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Done.

Before the loop begins, the variable $num is set to 1. This is called initializing a counter variable. Each time the code block executes, it increases the value in $num by 1 with the statement $num++;. After 10 iterations, the evaluation $num <= 10 becomes FALSE, then the loop stops and it prints Done. Be sure to increase the $num var, as the while loop depends on it.

Warning

Be careful not to create an infinite loop. It has the undesirable effect of not returning your page and taking a lot of processing time on the web server.

do ... while Loops

The do ... while loop takes an expression such as a while statement but places it at the end. The syntax is:

do {
  code to execute;
} while (expression);

This loop is useful when you want to execute a block of code at least once regardless of the expression value. For example, let's count to 10 with this loop, as shown in Example 4-15.

Example 4-15. Counting to 10 with do ... while

<?php

$num = 1;

do {
    echo "Number  is ".$num."<br />";
    $num++;
} while ($num <= 10);

echo "Done.";

?>

Example 4-15 produces the same results as Example 4-14; if you change the value of $num to 11, the loop processes differently:

<?php

$num = 11;

do {
    echo $num;
    $num++;
} while ($num <= 10);

?>

This produces:

11

The code in the loop displays 11 because the loop always executes at least once. Following the pass, while evaluates to FALSE, causing execution to drop out of the do ... while loop.

for Loops

for loops provide the same general functionality as while loops, but also provide for a predefined location for initializing and changing a counter value. Their syntax is:

for (initialization expression; condition expression; modification expression){
  code that is executed;
}

Figure 4-4 shows a flowchart for a for loop.

How a for loop executes

Figure 4-4. How a for loop executes

An example for loop is:

<?php
for ($num = 1; $num <= 10; $num++) {
    print "Number is $num<br />\n";
}
?>

This produces the following:

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10

When your PHP program process the for loop, the initialization portion is evaluated. For each iteration of the portion of code that increments, the counter executes and is followed by a check to see whether you're done. The result is a much more compact and easy-to-read statement.

Tip

When specifying your for loop, if you don't want to include one of the expressions, such as the initialization expression, you may omit it, but you must still include the separating semicolons (;). Example 4-16 shows the usage of a for loop without the initialization expression.

Breaking Out of a Loop

PHP provides the equivalent of an emergency stop button for a loop: the break statement. Normally, the only way out of a loop is to satisfy the expression that determines when to stop the loop. If the code in the loop finds an error that makes continuing the loop pointless or impossible, you can break out of the loop by using the break statement. It's like getting your shoelace stuck in an escalator. It really doesn't make any sense for the escalator to keep going! But those old-fashioned ones did!

Possible problems you might encounter in a loop include running out of space when you're writing to a file or attempting to divide by zero. In Example 4-16, we simulate what can happen if you divide based on an unknown entry initialized from a form submission (that could be a user-supplied value). If your user is malicious or just plain careless, she might enter a negative value where you're expecting a positive value (although this should be caught in your form validation process). In the code that's executed as part of the loop, the code checks to make sure the $counter is not equal to zero. If it is, the code calls break.

Example 4-16. Using break to avoid division by zero

<?php

$counter = −3;

for (; $counter < 10; $counter++){
    // Check for division by zero
    if ($counter == 0){
        echo "Stopping to avoid division by zero.";
        break;
    }

    echo "100/$counter<br />";
}

?>

This displays the following:

100/-3
100/-2
100/-1
Stopping to avoid division by zero.

Of course, there may be times when you don't want to just skip one execution of the loop code. The continue statement performs this for you.

continue Statements

You can use the continue statement to stop processing the current block of code in a loop and jump to the next iteration of the loop. It's different from break in that it doesn't stop processing the loop entirely. You're basically skipping ahead to the next iteration. Make sure you are modifying your test variable before the continue statement, or an infinite loop is possible. Example 4-17 shows the preceding example using continue instead of break.

Example 4-17. Using continue instead of break

<?php

$counter=-3;

for (;$counter<10;$counter++){
    //check for division by zero
    if ($counter==0){
        echo "Skipping to avoid division by zero.<br>";
        continue;
    }

    echo "100/$counter ",100/$counter,"<br />";
}

?>

The new output is as follows:

100/−3 −33.3333333333
100/−2 −50
100/−1 −100
Skipping to avoid division by zero.
100/1 100
100/2 50
100/3 33.3333333333
100/4 25
100/5 20
100/6 16.6666666667
100/7 14.2857142857
100/8 12.5
100/9 11.1111111111

Notice that the loop skipped over the $counter value of zero but continued with the next value.

We've now covered all of the major program flow language constructs. We've discussed the building blocks for controlling program flow in your programs. Expressions can be as simple as TRUE or FALSE or as complex as relational comparison with logical operators. The expressions combined with program flow control constructs like the if statement and switch make decision-making easy.

We also discussed while, do ... while, and for loops. Loops are very useful for common dynamic web page tasks such as displaying the results from a query in an HTML table.

Chapter 4 Questions

Question 4-1

What is a statement?

Question 4-2

What is a code element that acts on an expression?

Question 4-3

What does an operator combine?

Question 4-4

What is the plus (+) sign?

Question 4-5

What is a binary operator?

Question 4-6

What is a ternary operator?

Question 4-7

Do mathematical operators take letters as operands?

Question 4-8

What type of operand is an Array Index?

Question 4-9

If you use two ampersands (&&) instead of one (&), will you get an error?

Question 4-10

What does isset( ) do?

Question 4-11

Write a switch statement that adds, subtracts, multiplies, or divides x using the action variable.

Question 4-12

What does the break keyword do?

Question 4-13.

Write a for loop to count from 10 to 1.

See the "Chapter 4" section in the Appendix for the answers to these questions.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required