Conditional statements are required in every programming language. These statements execute different parts of the code depending on which condition gets satisfied. I have explained the commonly used conditional statements in this article. We shall begin with the if-then-else statement.
if-then-else Conditional Statement
The if-then-else instruction, through which it is possible to manage the application's logic flow, has the following syntax in PHP
PHP Code:
if (condition)
instruction1;
else
instruction2;
The condition in the above statement is a boolean expression that generally consists of a comparison between a variable and a constant value or a comparison between two variables. A boolean expression returns a true or false value. If a true value is returned, instruction1 is executed, otherwise, if a false value is returned, instruction2 is executed.
Look at the following example code
PHP Code:
<HTML>
<BODY>
<?
$Lastname = "Bit";
if ($Lastname == "Bit")
echo ("Hello, Mr. Bit!");
else
echo ("Who are you?");
?>
</BODY>
</HTML>
It will produce the following output
Hello, Mr. Bit!
The program checks the following boolean expression (condition) $Lastname == "Bit", that turns out to be true; so the immediately following echo() statement is executed. The second echo() statement, contained in the else branch, will NOT be executed.
To execute comparisons between variables and/or constant values, you can use the following comparison operators.
Code:
Comparison Operator
Description
==
Checks if 1st value is equal to 2nd value
>
Checks if 1st value is greater than 2nd value
<
Checks if 1st value is lesser than 2nd value
!=
Checks if 1st value is not equal to 2nd value
>=
Checks if 1st value is greater than or equal to 2nd value
<=
Checks if 1st value is lesser than or equal to 2nd value
Note that the 'equal to' operator (==) is expressed by two symbols "=" (equal) placed side by side ("=="). One of the most common errors is to use a "=" while using a boolean expression (comparing two variables, for instance). This kind of error seriously alters the logic flow of the program. Look at the following 2 statements
PHP Code:
if ($Lastname == "Bit") echo "Hello, Mr. Bit!";
if ($Lastname = "Bit") echo "This statement will always be printed";
The first instruction is processed as a comparison operation and it returns a true value if the variable $Lastname stores the value "Bit", false otherwise. The message "Hello, Mr. Bit!" would only be displayed if the condition turned out to be true.
The second instruction instead assigns the value "Bit" to the variable $Lastname. And this always turns out to be true. Since its just a normal assignment and not a conditional check. Thus the message in case always gets printed.
HTML Intermingled with PHP
PHP provides some alternative ways to write an if-then-else statement. Here is the first one
PHP Code:
<? ...
if (condition) : ?>
HTML instruction
<? else : ?>
HTML instruction
<? endif ?>
The condition is followed by a first block of HTML instructions that will be executed only if the condition returns a true value. The else keyword is followed by a second HTML block that will be executed if the condition returns a false value. The if-then-else statement finishes with the endif keyword.
The following PHP code is functionally analogous to the first example of this chapter
PHP Code:
<HTML>
<BODY>
<?
$Surname = "Bit";
if ($Surname == "Bit"): ?>
Hello, Mr. Bit!
<? else: ?>
Who are you?
<? endif ?>
</BODY>
</HTML>
The output will be obviously the same
Hello, Mr. Bit!
If we have more than one instruction to be carried out in a if... then... else... structure, it is necessary to enclose them in the brackets { and } . The brackets task is to create a block where more instructions can be held together. Otherwise we can use the endif keyword as it follows
PHP Code:
if (condition)
instruction1;
instruction2;
...
instructionN;
endif;
When we are interested in analyzing more conditions before choosing the instruction to execute, we can create a if... then... else... chain structure. This allows us to specify a set of conditions that will be checked up sequentially. Each condition is checked up only if all the previous ones have returned a false value. When the first true condition is found, all the successive ones will not be processed. The syntax of an if... then... else... chain instruction is the following
PHP Code:
if (condition)
instruction1;
elseif
instruction2;
elseif
instruction3;
.
.
.
else
instructionN;
The if-then-else statement can also be used along with boolean logic operators AND, OR and NOT. Such operators are expressed in PHP with special symbols shown below
Logical Operator
&& : Boolean AND
|| : Boolean OR
^ : Boolean XOR
!: Boolean NOT
The use of these operators allows you to write sophisticated boolean expressions that will be evaluated using something called the truth tables.
Switch Conditional Statement
When it is required to execute a set of comparisons on the same variable, instead of writing an if-else-else instruction, we are used to choose the switch one. Its syntax is as follows
PHP Code:
switch ($VarName){
case V1:
Instruction1;
break;
case V2:
Instruction2;
break;
.
.
.
.
case VN:
InstructionN;
break;
default:
Instruction;
break;
}
$VarName is the variable on which comparisons are performed, while V1, V2, V3 are variables or constant values to which $VarName is compared to. When one of the comparison operation returns a true value the corresponding instruction is executed. If no comparison return a true value, the instruction held in the default branch is executed.
Suppose, for instance, that we need to compare the value of an integer variable named $var, with a collection of integer constants. We'll write
PHP Code:
<?
$var=2;
switch ($var) {
case 1:
echo ("\$var isn't 1");
break;
case 2:
echo ("\$var isn't 2");
break;
case 5:
echo ("\$var isn't 5");
break;
default:
echo ("\$var value isn't 1, 2 or 5, but $var");
break;
}
?>
We could get the same result by writing an if-else-else instruction as it follows
PHP Code:
<?
$var=2;
if ($var==1)
echo ("\$var value isn't 1");
elseif ($var==2)
echo ("\$var value isn't 2");
elseif ($var==1)
echo ("\$var value isn't 3");
else
echo("\$var value isn't 1, 2, or 5, but $var");
?>
Observe that the escape character (" \ ") has been used before the name of the variable. Its purpose is to visualize the '$' character, avoiding that the $var variable is interpreted and replaced with its value. We'll talk about the escape sequences in later articles.
For Loops - The most used Conditional Statement
Another useful instruction that controls the logic flow of the program, is the for statement. It allows software developers to execute one or more instructions many times, until a particular condition is satisfied. It's called the condition of escape (or exit condition) for the loop.
The PHP syntax of a for loop instruction is the following one
PHP Code:
for ($v=startValue; condition_on_$v; instruction_on_$v){
LoopBody;
}
$v is the control variable of the cycle. $v is initialized to the value startValue when the loop begins. condition_on_$v is the condition of control for the loop. The loop ends when condition_on_$v returns a false value (that's to say when the condition_on_$v no longer is true). The first check on the condition is carried out before the first iteration; therefore, it is possible that the instructions held in the body of the loop (LoopBody) are never executed. This happens when condition_on_$v immediately returns a false value. instruction_on_$v is an instruction that modifies the value of the control variable $v. With this instruction $v generally moves towards a value that makes condition_on_$v false; in this way the loop execution ends. This should happen after a certain number of iterations. If condition_on_$v never turns out to be false, the risk would be to generate an infinite loop, that to say a never ending loop. All this would be more clear when you read an example.
Here are some examples in which the for loop is used.
The first example simply prints the numbers from one to ten. I have shown you only a part of the complete code. This should be enough to understand. A more complex and complete example is shown later.
PHP Code:
for($k=1 ; $k<=10 ; $k++){
echo("$k<TR>");
}
The control variable of the loop is $k. It is first declared and then initialized to the value 1 at the cycle's beginning. The control condition of the cycle returns a true value until $k is lesser than or equal to 10. The instruction on $k consists of incrementing $k after every iteration. The body of the loop consists of a echo() instruction.
In the first iteration $k has been just initialized to the value 1. The output of the first iteration will be 1. In the second iteration, $k has assumed value 2, therefore the output of the echo() instruction will be 2. The cycle repeats until $k assumes a value of 11. At this step the condition of control ($k <= 10) turns out false and the cycle exits.
The output of the program is
1
2
3
4
5
6
7
8
9
10
The second example uses a for loop to create an HTML Table
PHP Code:
<HTML>
<BODY>
<?
echo ("<TABLE ALIGN=CENTER BORDER=1 CELLSPACING=1 CELLPADDING=5 >");
for ($j=1;$j<=5;$j++) {
echo ("<TR>");
for ($k=1;$k<=3;$k++)
echo ("<TD> Line $j, Cell $k </TD>");
echo("</TR>");
}
echo ("</TABLE>");
?>
</BODY>
</HTML>
The above code generates the following output
Line 1, Cell 1 Line 1, Cell 2 Line 1, Cell 3
Line 2, Cell 1 Line 2, Cell 2 Line 2, Cell 3
Line 3, Cell 1 Line 3, Cell 2 Line 3, Cell 3
Line 4, Cell 1 Line 4, Cell 2 Line 4, Cell 3
Line 5, Cell 1 Line 5, Cell 2 Line 5, Cell 3
That's all for this article. More in the next one..
View more threads in the same category:
Bookmarks