|
|
Decisions I - The if Statement
The if Statement
To make a script do something truly useful, we often need to execute different code depending on the value of a variable. To do this, we can use an if statement, the simplest form of which is:
if (condition) {
//Do something.
}
In this case, PHP will evaluate 'condition' and determine whether it is true or false. If it is true, the code within the braces ({})will be executed. Otherwise, it will be ignored. The condition may be a variable, function, or arithmetic expression. For example:
if (2 + 40 == 42) {
echo("The answer is 42.");
}
if (2 + 40 != 42) {
echo("The answer is not 42.");
}
Will output:
The answer is 42.
Note the use of the double equals (==) comparison operator in this expression. In PHP, a single = is used for assignment - to set the value of a variable. A double equals is used for comparison, to determine whether one value is equal to another. If we had used, for example if($a = $b), this would always return true, regardless of the values of the variables $a and $b. This is because using the single equals sign, PHP is not checking whether $a is equal to $b, but is setting $a equal to $b.
This code block also introduces another new operator - the not equal to operator (!=). This evaulates to true if the operands (values either side) are not equal. PHP also supports another 'not equal to' operator - <> - both are identical in operation, but programmers familiar with languages such as BASIC may be more familiar with the latter. Other comparison operators available in PHP include:
The if...else Statement
The if...else statement expands upon the standard if statement and provides added flexibility. It takes the form:
if(condition) {
//Do something if condition is true.
}else{
//Do something different if condition is false.
}
Here, the code within the first set of braces will be executed if 'condition' is true, otherwise the code within the second set will be executed. Our example from above may be rewritten more efficiently as:
if(2 + 40 == 42) {
echo("The answer is 42.");
} else {
echo("The answer is not 42.");
}
The if...elseif...else Statement
This allows the computer to select one of several blocks of code to execute. An if...elseif...else statement takes the form:
if(first_condition) {
//Do something if first_condition is true.
} elseif(second_condition) {
//Do something if first_condition is false but second_condition is true.
} else {
//Do something if neither condition is true.
}
All three of these statements are in fact, different variations of the same basic if construct. In any if statement there must be exactly one if block, zero or more elseif blocks, and zero or one else blocks.
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
|