Sunday, May 29, 2011

PHP Lesson 3: Controlling the Flow of the Program

Quick Review:

In PHP Lesson 1, we learned how to install PHP, how to use nano to enter and save the source code of a program, and how to use php to run the program. We then used nano again to edit it to make corrections, and finally used php to run it again and show the updated output.

In PHP Lesson 2, we learned how to use expressions consisting of operators and operands to manipulate numeric, boolean, and string values and to store them in and retrieve them from variables.

Controlling the Flow of the Program

So far, our programs have only been able to run line by line (technically, statement by statement), in sequence from beginning to end. In this lesson we are going to learn several language constructs which allow us to control the order in which the statements in a program are executed.

First of all, what is a language construct?

A language construct (or a "control structure") is one of the allowable pieces of syntax that can be used within a program's source code. We've already learned two language constructs:

In PHP, the most primitive language constructs is a simple expression. The most basic or common expression is simply an assignment operation such as:
$x = 3;
Another PHP language construct is echo, which takes an expression (often a simple value) and turns its result into part of the program's output, such as:
echo "Hello";
Conditional Constructs

There are several forms of the if statement. The simplest form looks like this:
if (condition) outcome;
condition must be replaced with an expression resulting in a boolean (true/false) value. Frequently, a comparison operator such as ==, <, <=, >, >=, or != is used in this expression.

outcome should be replaced with the actual statement to be executed if and only if the condition is found to be true.

For example:
if ($x == 3) echo "Three!";
The value of $x is compared with 3, and if they are equal, the result of the expression is true. If the result is true, the outcome part of the if statement is executed, otherwise nothing happens and execution proceeds with the next statement.

Often, we wish to execute a whole sequence of commands based upon a certain condition. To do this, we may use a compound statement for the outcome part of the if statement.

A compound statement is another language construct which may be used anywhere in your program where a single statement would ordinarily be permitted. A compound statement is formed by enclosing statements within a set of curly braces. The curly braces and all of the statements which are contained therein are treated as if they were a single statement.

The if statement and a compound statement may be combined like this:
if ($x == 3) {
   $x =4;
   echo "This is a compound statement to inform you ";
   echo "that the value of $x was 3, but has now been changed to 4.";
}
Although the purpose of a compound statement is to combine several statements into one, it is perfectly legal to make a compound statement that contains only a single statement inside of it. I, along with many other sources, recommend always using the compound statement braces whenever writing out an if statement (as well as when writing out most of the other language constructs which you will be learning later.) The reasons for always writing them are to improve readability, and to make it simpler to adjust the program later because there will already be a place ready to insert additional lines of code.

The if statement has other forms as well. The next one we will learn is the if/else statement:
if (condition) outcome; else alternateOutcome;
With braces, this looks like:
if (condition) {
    outcome;
} else {
   alternateOutcome;
}
Technically, you may choose to omit the braces on either one of the two outcome clauses while including them on the other, although once again, it is my recommendation to always use them:
if (condition) {
   outcome;
} else alternateOutcome;

The if/elseif statement:

Sometimes it isn't a question of doing one thing or the other, but rather, a series of several possible outcomes, based upon different conditions.
if (condition) outcome; elseif (secondCondition) secondOutcome; else alternateOutcome;
Or, with braces:
if (condition) {
   outcome;
} elseif (secondCondition) {
   secondOutcome;
} else {
   alternateOutcome;
}
You may have as many elseif sections as you wish. They are tested in order from top to bottom, and only the first matching condition has its outcome executed. If none of the conditions are true, the alternate outcome listed in the else clause is executed. The else clause, however, is optional. If omitted, and none of the listed conditions are matching, execution will simply continue with the statement following the entire if/elseif structure.

There is one other Conditional Construct which we will cover in a future lesson.

Looping Constructs

Sometimes we want something to happen more than once. That's what a loop is for. There are several types of looping constructs available in PHP, but in this lesson we will cover only the one with the widest range of usefulness:

The While Loop

The while loop looks like this:
while (condition) loopBody;
If the condition is true, the loopBody is executed. After this, the condition is checked again, and if it is still true, the loopBody is executed again, and so forth, until the condition is found to be false. If the condition is never false, an "infinite loop" may be created and the program will have to be forcefully terminated in order to get it to stop.

You may notice that this is just like the basic if statement, except that instead of executing the outcome only once, it continues executing the provided statement(s) until the condition has become false. As with the if statement, the loopBody should probably be written as a compound statement for clarity. Here is a sample of a while loop in action:
$x = 10;
while ($x > 0) {
   echo "Looping!\r\n";
   $x--; // decrease the value of $x by 1
}
This loop will echo the message Looping! ten times before stopping.

That's it for now!

Next Post: I/O

No comments:

Post a Comment