by Kevin Yank of SitePoint.com
Control Structures
All the examples of PHP code that we have seen so far have been either simple one-statement scripts that output a string of text to the Web page, or have been series of statements that were to be executed one after the other in order. If you've ever written programs in any other language (be it JavaScript, C, or BASIC) you already know that practical programs are rarely so simple.
PHP, just like any other programming language, provides facilities for affecting the "flow of control" in a script. That is, the language contains special statements that permit you 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-else
statement. Here's what it looks like:
if ( <condition> ) {
// Statement(s) to be executed if
// <condition> is true.
} else {
// (Optional) Statement(s) to be
// executed if <condition> is false.
}
This control structure lets us tell PHP to execute one set of statements or another depending on whether some condition is true or false. If you'll indulge my vanity for a moment, here's an example that shows a twist on the welcome.php
file we created earlier:
if ( $name == "Kevin" ) {
echo( "Welcome, oh glorious leader!" );
} else {
echo( "Welcome, $name!" );
}
Now, if the name variable passed to the page has a value of Kevin
, a special message will be displayed. Otherwise, the normal message will be displayed containing the name entered.
As indicated in the code structure above, the "else
clause" (that part of the if-else
statement that says what to do if the condition is false) is optional. Let's say you wanted to display the special message above if the appropriate name was entered, but otherwise not display anything. Here's how the code would look:
if ( $name == "Kevin" ) {
echo( "Welcome, oh glorious leader!" );
}
The ==
used in the condition above is the PHP operator used for comparing two values to see if they are equal. It's important to remember to type the double-equals, because if you were to use a single equals sign you'd be using the assignment operator discussed above, and instead of comparing the variable with the designated value you would be assigning a new value to the variable (an operation which, incidentally, evaluates as true). This would not only cause the condition to always be true, but might change the value in the variable you were checking, causing all sorts of potential problems.
A safeguard against making this common mistake is to swap the positions of the variable and the constant value in the comparison as follows:
if ( "Kevin" == $name ) {
This has exactly the same effect, but look what happens if you mistakenly use a single equals sign. PHP will attempt to assign the value of the variable ($name
) to the constant value ("Kevin"
). Since you can't change the value of a constant, PHP will choke and display an error message, immediately drawing your attention to the fact that you forgot the second equals sign!
Conditions can be more complex than a single comparison for equality. Recall that we modified welcome.php3
to take 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:
if ( "Kevin" == $firstname and "Yank" == $lastname ) {
echo( "Welcome, oh glorious leader!" );
}
This condition will be true if and only if $firstname
has a value of Kevin
and $lastname
has a value of Yank
. The word and
in the above condition makes the whole condition true only if both of the comparisons evaluate to true. Another such operator is or
, 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), they work in PHP as well.
We'll look at more complicated comparisons as the need arises. For the time being, a general familiarity with the if-else
statement 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 to repeatedly execute a set of statements. Here's what a while
loop looks like:
while ( <condition> ) {
// statement(s) to execute over
// and over as long as <condition>
// remains true
}
This works very similarly to an if-else
statement without an else clause. The difference arises when the condition is true and the statement(s) are executed. Instead of continuing execution with the next statement following 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 one-hundred-and-first), execution jumps immediately to the next statement following the while loop (after the closing brace).
Loops like these come in handy whenever you're working with long lists of things (such as jokes stored in a database... hint-hint!), but for now we'll illustrate with a trivial example: counting to ten.
$count = 1;
while ($count <= 10) {
echo( "$count " );
$count++;
}
Kind of scary-looking, I know, but let me talk you through it line by line. The first line creates a variable called $count
and assigns it a value of 1
. The second line is the beginning of a while
loop, the condition for which is that the value of $count
is less than or equal (<=
) to 10
. The third and fourth lines make up the body of the while
loop, and will be executed over and over as long as that condition holds true. The third line simply outputs the value of $count
followed by a space. The fourth line adds one to the value of $count
($count++
is a shortcut for $count = $count + 1
-- both will work).
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 is checked, so the value (2
) is output and a new value of 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 false, ending the loop. The net result of the code is to output the string "1 2 3 4 5 6 7 8 9 10
".
The condition we used 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.
Multi-Purpose Pages |
SitePoint.com is a fast growing Web Developer Community. Kevin Yank is the Editor of the SitePoint TechTimes, a fresh, technically oriented newsletter for the serious Webmaster. |