Article

Build Your Own Database Driven Web Site using PHP & MySQL, Part 3: Introducing PHP

Page: 1 2 3 4 Next

Control Structures

All the examples of PHP code we’ve seen so far have been either one-statement scripts that output a string of text to the web page, or series of statements that were to be executed one after the other in order. If you’ve ever written programs in other languages (JavaScript, C, or BASIC) you already know that practical programs are rarely so simple.

PHP, just like any other programming language, provides facilities that enable you to affect the flow of control. That is, the language contains special statements that you can use to deviate from the one-after-another execution order that has dominated our examples so far. Such statements are called control structures. Don’t understand? Don’t worry! A few examples will illustrate perfectly.

The most basic, and most often used, control structure is the if statement. The flow of a program through an if statement can be visualized as in the figure below.

The logical flow of an if statement

(This diagram and several similar ones in this book were originally designed by Cameron Adams for the book, Simply JavaScript (Melbourne: SitePoint, 2006), which we wrote together. I have reused them here with his permission, and my thanks.)

Here’s what an if statement looks like in PHP code:

if (condition)  
{  
 // conditional code to be executed if condition is true  
}

This control structure lets us tell PHP to execute a set of statements only if some condition is met.

If you’ll indulge my vanity for a moment, here’s an example that shows a twist on the personalized welcome page example we created earlier. Start by making a copy of welcome6.html called welcome7.html. For simplicity, let’s alter the form it contains so that it submits a single name variable to welcome7.php:

<form action="welcome7.php" method="post">  
 <div><label for="name">Name:  
   <input type="text" name="name" id="name"/></label></div>  
 <div><input type="submit" value="GO"/></div>  
</form>

Now make a copy of welcome6.php called welcome7.php. Replace the PHP code it contains with the following:

$name = $_REQUEST['name'];  
if ($name == 'Kevin')  
{  
 echo 'Welcome, oh glorious leader!';  
}

Now, if the name variable passed to the page has a value of 'Kevin', a special message will be displayed, as shown below.

It’s good to be the king

If a name other than Kevin is entered, this example becomes inhospitable—the conditional code within the if statement fails to execute, and the resulting page will be blank!

To offer an alternative to a blank page to all the plebs who have a different name to Kevin, we can use an if-else statement instead. The structure of an if-else statement is shown below.

The logical flow of an if-else statement

The else portion of an if-else statement is tacked onto the end of the if portion, like this:

$name = $_REQUEST['name'];  
if ($name == 'Kevin')  
{  
 echo 'Welcome, oh glorious leader!';  
}  
else  
{  
 echo 'Welcome to our web site, ' .  
     htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '!';  
}

Now if you submit a name other than Kevin, you should see the usual welcome message shown below.

You gotta remember your peeps

The == used in the condition above is the equal operator that’s used to compare two values to see whether they’re equal.
Double Trouble

Remember to type the double-equals (==). A common mistake among beginning PHP programmers is to type a condition like this with a single equals sign:

if ($name = 'Kevin')     // Missing equals sign!

This condition is using the assignment operator (=) that I introduced back in the section called “Variables, Operators, and Comments”, instead of the equal operator (==). Consequently, instead of comparing the value of $name to the string 'Kevin', it will actually set the value of $name to 'Kevin'. Oops!

To make matters worse, the if statement will use this assignment operation as a condition, which it will consider to be true, so the conditional code within the if statement will always be executed, regardless of what the original value of $name happened to be.

Conditions can be more complex than a single check for equality. Recall that our form examples above would receive a first and last name. If we wanted to display a special message only for a particular person, we’d have to check the values of both names.

To do this, first make a copy of welcome6.html (which contains the two-field version of the form) called welcome8.html. Change the action attribute of the <form> tag to point to welcome8.php. Next, make a copy of welcome7.php called welcome8.php, and update the PHP code to match the following:

$firstname = $_REQUEST['firstname'];  
$lastname = $_REQUEST['lastname'];  
if ($firstname == 'Kevin' and $lastname == 'Yank')  
{  
 echo 'Welcome, oh glorious leader!';  
}  
else  
{  
 echo 'Welcome to our web site, ' .  
     htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' .  
     htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!';  
}

This updated condition will be true if and only if $firstname has a value of 'Kevin' and $lastname has a value of 'Yank'. The and operator in the condition makes the whole condition true only if both of the comparisons are true. A similar operator is the or operator, which makes the whole condition true if one or both of two simple conditions are true. If you’re more familiar with the JavaScript or C forms of these operators (&& and || for and and or respectively), that’s fine—they work in PHP as well.

The figure below shows that having only one of the names right in this example fails to cut the mustard.

Frankly, my dear ...

We’ll look at more complicated conditions as the need arises. For the time being, a general familiarity with if-else statements is sufficient.

Another often-used PHP control structure is the while loop. Where the if-else statement allowed us to choose whether or not to execute a set of statements depending on some condition, the while loop allows us to use a condition to determine how many times we’ll execute a set of statements repeatedly.

This figure shows how a while loop operates.

The logical flow of a while loop

Here’s what a while loop looks like in code:

while (condition)  
{  
 // statement(s) to execute repeatedly as long as condition is true  
}

The while loop works very similarly to an if statement. The difference arises when the condition is true and the statement(s) are executed. Instead of continuing the execution with the statement that follows the closing brace (}), the condition is checked again. If the condition is still true, then the statement(s) are executed a second time, and a third, and will continue to be executed as long as the condition remains true. The first time the condition evaluates false (whether it’s the first time it’s checked, or the 101st), the execution jumps immediately to the statement that follows the while loop, after the closing brace.

Loops like these come in handy whenever you’re working with long lists of items (such as jokes stored in a database … hint, hint), but for now I’ll illustrate with a trivial example, counting to ten:

$count = 1;  
while ($count <= 10)  
{  
 echo "$count ";  
 ++$count;  
}

This code may look a bit frightening, I know, but let me talk you through it line by line:

$count = 1;

The first line creates a variable called $count and assigns it a value of 1.
while ($count <= 10)

The second line is the start of a while loop, the condition for which is that the value of $count is less than or equal (<=) to 10.
{

The opening brace marks the beginning of the block of conditional code for the while loop. This conditional code is often called the body of the loop, and is executed over and over again, as long as the condition holds true.

echo "$count ";

This line simply outputs the value of $count, followed by a space. To make the code as readable as possible, I’ve used a double-quoted string to take advantage of variable interpolation (as explained in the section called “Variables, Operators, and Comments”), rather than use the string concatenation operator.
++$count;

The fourth line adds one to the value of $count (++$count is a shortcut for $count = $count + 1—either one would work).
}

The closing brace marks the end of the while loop’s body.

So here’s what happens when this piece of code is executed. The first time the condition is checked, the value of $count is 1, so the condition is definitely true. The value of $count (1) is output, and $count is given a new value of 2. The condition is still true the second time it’s checked, so the value (2) is output and a new value (3) is assigned. This process continues, outputting the values 3, 4, 5, 6, 7, 8, 9, and 10. Finally, $count is given a value of 11, and the condition is found to be false, which ends the loop.

The net result of the code is shown below.

PHP demonstrates kindergarten-level math skills

The condition in this example used a new operator: <= (less than or equal). Other numerical comparison operators of this type include >= (greater than or equal), < (less than), > (greater than), and != (not equal). That last one also works when comparing text strings, by the way.

Another type of loop that’s designed specifically to handle examples like that above, in which we’re counting through a series of values until some condition is met, is called a for loop. The figure below shows the structure of a for loop.

The logical flow of a for loop

Here’s what it looks like in code:

for (declare counter; condition; increment counter)  
{  
 // statement(s) to execute repeatedly as long as condition is true  
}

The declare counter statement is executed once at the start of the loop; the condition statement is checked each time through the loop, before the statements in the body are executed; the increment counter statement is executed each time through the loop, after the statements in the body.

Here’s what the “counting to 10” example looks like when implemented with a for loop:

for ($count = 1; $count <= 10; ++$count)  
{  
 echo "$count ";  
}

As you can see, the statements that initialize and increment the $count variable join the condition on the first line of the for loop. Although, at first glance, the code seems a little more difficult to read, putting all the code that deals with controlling the loop in the same place actually makes it easier to understand once you’re used to the syntax. Many of the examples in this book will use for loops, so you’ll have plenty of opportunity to practice reading them.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links