Control statements are fundamental to programming languages. Control statements permit you to take some action if something is the case, and different action (or no action) otherwise. There are three common control statements in PHP:
$IP_address = getenv("REMOTE_ADDR");
if ( $IP_address == "121.114.221.111" ) {
echo "Hello, George. Welcome to my web site.");
}
else {
echo "Howdy, stranger.";
}
$temperature = 71;
if ( $temperature >= 50 ) {
echo "Nice day!";
}
|
$a = 2;
while ( $a < 100 ) {
echo " $a";
$a *= $a;
}
$b = 1;
while ( $b < 10 ) {
$a++;
} // OOPS! This is an infinite loop!
|
$sum = 0;
for ( $a = 1; $a <= 10; $a++ ) {
$sum += $a;
}
echo "Sum of numbers from 0 to 10 equals $sum.";
//
// The for loop is just shorthand for the following while loop:
//
$a = 1;
while ( $a <= 10 ) {
$sum += $a;
$a++;
}
|
As you can see from the examples, the condition is tested using commonsense mathematical expressions. Indeed, here are the PHP comparison operators:
> (greater than)
< (less than)
<= (less than or equal to)
>= (greater than or equal to)
== (equal to; note that two equal signs are used to distinguish it from an assignment)
!= (not equal to)
There also are Boolean operators that allow you to combine conditional expressions:
&& (and)
|| (or)
! (not)
For instance, ( $a > 5 ) && ( $a < 20 ) tests whether the value of $a is greater than 5 and less than 20. The expression ( $name != "John" ) || ( $age >= 18 ) tests whether $name is not equal to "John" or $age is greater than or equal to 18.
Finally, !( ( $sky == "cloudy" ) || ( $temperature < 50 ) ) tests whether it is not the case that $sky equals "cloudy" or $temperature is less than 50. For instance you might write the following:
$sky = "sunny";
$temperature = 65;
if ( !( ( sky == "cloudy" ) || ( $temperature < 50 ) ) ) {
echo "Nice day.";
}
Else {
echo "Lousy day.";
}
|