Learning PHP: volume 4
This tutorial covers all the statements you use to control the flow through your script, including making decisions with if(), else, and elseif(), and then talks about an alternative syntax. The switch() statement can be a great replacement for long sets of if() statements and is similar to the select statement availbable in other languages. The while() and for() statements let you loop through code based on certain conditions and seem to work like while() and for() in other languages.
The include() and require() statements let you include code from other files, and both work like their equivalents in C. There are a couple of traps to be aware of when using them in PHP, and the new require_once() and include_once() statements help to recude the common problem of including files more than once.
if()
Coding with if() in PHP is similar to coding with if() in other languages. This section will describe the shortcuts for coding with if() in PHP, plus show you some traps to avoid. The next example is a short piece of code to test the value of $a and print "ok" if $a is greater than zero:
PHP Code:
if($a > 0) {
print("ok");
}
PHP interprets zero as false, everything greater than zero as true, and everything less than zero as true. Some other languages consider negative numbers to be false, so that can be a trap if you are processing data from other systems. Because PHP automatically converts character data to integer, 0 is also treated as false, as is the zero-length string. If you coded if($a == false), 0 and "" would both produce false results, so you have to code if($a === false).
PHP converts fields straight to logical values, so you can reduce if($a != 0) to if($a) and PHP will convert $a to true or false for if(). You can also code if statements in the form if(!$a) to perform something when $a is false. All these variations can expose you to unintended results, so consider the formal comparison of value and type as in if($a === true) and if($a === false).
The if allows for multiple conditions joined by and, or and structured with parentheses (). Because the conditions are evaluated from left to right, you can check if a variable exists before testing for a value in the variable. The following example will stop at the isset() if $a is not defined, so it will not generate an error message for a missing $a. This is a short example of the code you can use when testing for optional variables that may not exist, such as field from a form:
PHP Code:
if(isset($a) and $a > 0) {
print("ok");
}
else
The else statement gives you a great way to cover all values, and it works the same as in all other languages. You use it after an if(), as shown in the following example:
PHP Code:
if($a == $b) {
print("equal");
} else {
print("not equal");
}
elseif()
The elseif() statement lets you step through various conditions using if() statements and is similar to elseif() and else if in other languages:
PHP Code:
if($a == "hot") {
print("Turn on air-conditioner");
} elseif($a == "warm") {
print("Enjoy the weather");
} else {
print("Turn on heater");
}
switch()
The code example in elseif() can be represented as a multiple selection using switch(). The code based in switch is easier to maintain when there are many possible values and actions. Here is the code from the previous section redone using switch():
PHP Code:
switch($a) {
case "hot":
print("Turn on air-conditioner");
break;
case "warm":
print("Enjoy the weather");
break;
default:
print("Turn on heater");
}
The switch() statement tests a variable or expression, in this case $a, against the expression in the first case statement, "hot", and on a successful comparison, starts executing the code following the case statement. On failure, switch() jumps down to the next case statement and tries another comparison.
The default: statement is equivalent to the else statement with if() - it is the action that will be executed if all the case statements fail. The default: statement is not required, just as an else is not required after an if().
After switch() completes the code in a case statement, switch() keeps on going down the code, running the code unless you have a break statement to jump execution out of the switch(). (Some languages always jump out of their equivalent to switch() without the equivalent of a break, which means you cannot use the equivalent of the next example.) In the previous example, you might want "hot" to both turn on the air-conditioner and display the message about anjoying the weather. All you need to do to accomplish the change is leave out the break at the end of case "hot" as shown here:
PHP Code:
switch($a) {
case "":
print("Turn on air-conditioner");
case "":
print("Enjoy the weather");
break;
default:
print("Turn on heater");
}
Sometimes you want multiple values to cause the same action, and many languages allow the equivalent of multiple values on a case statement. PHP requires a case statement for each value, which makes it easier to document each value (with a comment on each line.) In the following example, the programmer likes the weather "hot", and you leaves the air-conditioner off.
PHP Code:
switch($a) {
case "hot":
case "warm":
print("Enjoy the weather");
break;
default:
print("Turn on heater");
}
while()
When you are reading an array or a file or rows returned from a database, you might like to use while() to control the program execution flow. The only competitor in PHP is for(), but I tend to use while() the most because while() fits better than for() with many PHP functions and constructs.
Many languages give you variations of while() to allow testing of conditions before or after a loop, so you can loop through your code at least once. PHP supplies a do while() statement for those occasions. The following example shows a standard while() loop that will run zero times because $a is already equal to $b. The second part of the code shows the do while() equivalent that runs at least once before testing for $a == $b. The first part prints zero lines, and the second part prints one line:
PHP Code:
$a = $b = 5;
while($a != $b) {
print("This will never print");
}
do {
print("This will print at least once");
} while($a != $b);
The while() loop works extremely well with list() and each() for stepping through arrays, as shown in the next example. The example builds a short array, resets the array pointer to the start of the array, and then uses while() to step through the array. The each() statement returns one array entry at a time, moves the array pointer to the next entry, and returns false at the end of the array. The list() statement takes the data from each() and places the array entry key in the first field, $k, and the array entry value in the second field, $v:
PHP Code:
$white_crystalline_substance[] = "C12H22O11";
$white_crystalline_substance[] = "C8H10N4O2.H2O";
$white_crystalline_substance[] = "NaCl";
reset($white_crystalline_substance);
print("Warning, the most abused and addictive substances are:");
while(list($k, $v) = each($white_crystalline_substance)) {
print("<br>" . $v);
}
Note that you do not need to provide an index value when creating an entry for an array; when PHP sees the empty square brackets, PHP automatically uses the next available index number.
When while() steps through the example, it loops through the code three times, once for each entry, and stops when each() returns false:
Code:
Warning, the most abused and addictive substances are:
C12H22011
C8H10N402.H20
NaC1
Bookmarks