Control Structures - PHP Programming: Learn PHP Programming - CRUSH IT IN ONE DAY. Learn It Fast. Learn It Once. Get Coding Today, First Edition(2015)

PHP Programming: Learn PHP Programming - CRUSH IT IN ONE DAY. Learn It Fast. Learn It Once. Get Coding Today, First Edition (2015)

Chapter 5. Control Structures

Control structures are used to change the flow of control by analyzing the variables and then choosing a direction to go basing on the parameters given. There are many control structures which are supported by PHP. Some of them are if, else, else if, while, do while, for, for each, break, continue, switch, declared etc.

Here we will discuss about these controls structures in detail.

if: in many languages, if is considered an important feature. Here the expression will be evaluated to its Boolean value and if the result is true then the statement will be executed by PHP. It can be explained by this simple program given below.

Example:

<?php

if ($a > $b)

echo "a is bigger than b";

?>

In the above example if ‘a’ is greater than ‘b’, the message will be displayed. If statements can be placed within one another and they are called nested if.

else:

The else control structure can be used in situations where you want to execute a certain set of instructions when a condition is satisfied and a different set when it is not satisfied. Else is an extension of the if control structure in case when the if statement evaluates FALSE. Here is an example where else is used.

Example:

<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>

Here if a is less than b, the output will be "a is NOT greater than b".

else if:

As the name suggests,“else if“is the combination of else and if. It extends the if statement like the else and will execute a different statement when the if statement is false. But unlike the statement, the alternate statement will be executed If the else if statement is true. Here is an example which will display a is bigger than b or a equal to b or a is smaller than b.

Example:

<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

There can be any number of else if statements within an if statement. The first else if statement which will be evaluated as true will be executed first. Here is an example to show the correct way to use the else if statement.

Example:

<?php

/* Incorrect Method: */
if($a > $b):
echo $a." is greater than ".$b;

else if($a == $b
): // Will not compile.
echo "The above line causes a parse error.";
endif;


/* Correct Method: */
if($a > $b):
echo $a." is greater than ".$b;
elseif($a == $b): //Note the combination of the words.
echo $a." equals ".$b;
else:
echo $a."
is neither greater than or equal to
".$b;
endif;

?>

While:

In PHP, while loop is the simplest type of loop. The basic syntax of a while loop is as follows.

while ( expr )

statement

The while statement will tell the PHP to repeatedly execute the nested statements. This will continue till the while statement evaluates to be true. The value of the expression with each iteration changes and it will only stop executing when the statement is satisfied. The expression evaluates to be false even before executing it once, it won't run even once. Here is an example to show the while loop. Both of them print numbers from 1 to 10.

Example:

<?php
/* example 1 */

$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>

do while:

The do-while loop is very much similar to the while loop but the truth expression will be checked towards the end of every iteration unlike the while statement, where it is checked in the beginning. So this will allow the statements to be executed once even if they evaluate to be false. There is only one syntax for the do-while loop.

Example:

<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>

Here in the above example, the statements evaluate to be false but this will execute the statements once before the loop ends.

The execution can be stopped in the middle by using the break statement and encapsulating them with do-while(0).

Example:

<?php
do {
if ($i < 5) {
echo "
i is not big enough
";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i is ok";

/*
process i */

} while (0
);
?>

for loop:

In PHP, the for loops are the most complex of all. The basic for loop syntax is

for (expr1; expr2; expr3)

Statement

At the beginning of the loop the first expression will be evaluated once unconditionally. The second expression will be evaluated on every iteration’s beginning. The loop will continue as long as it evaluates to be true and will terminate once it encounters a false. Expression 3 will be evaluated at the end of every iteration. Here are some examples which show how to use the loop in different ways.

<?php
/* example 1 */

for ($i = 1
; $i <= 10; $i++) {
echo $i;
}

/*
2 */

for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}

/*
example 4 */

for ($i = 1, $j = 0
; $i <= 10; $
j += $i, print $i, $i
++);
?>

Switch:

In PHP, the switch statement is very similar to a series of if statements which are on the same expression. You will encounter many situations where you need to compare the same variable with other different values. And then execute a different set of statements depending on the value obtained. Here we use the switch statement. In the below example, the same thing is written in two different ways. One is written using a series of if and else if statements. The other piece of code is written using the switch statement. The syntax for this switch statement is given below.

Syntax:

switch (expression )

{

case constant1:

execute the statement;

break;

case constant2:

execute the statement;

break;

case constant3:

execute the statement;

break;

.........

default;

execute the statement;

}

Example 1: using switch structure

<?php

if ($i == 0) {

echo "i equals 0";

} elseif ($i == 1) {

echo "i equals 1";

} elseif ($i == 2) {

echo "i equals 2";

}

switch ($i) {

case 0:

echo "i equals 0";

break;

case 1:

echo "i equals 1";

break;

case 2:

echo "i equals 2";

break;

}

?>

Example 2: Usage of strings is allowed in the switch structure

<?php

switch ($i) {

case "apple":

echo "i is apple";

break;

case "bar":

echo "i is bar";

break;

case "cake":

echo "i is cake";

break;

}

?>

In order to avoid mistakes, it is very important to learn how the switch statement will be executed. The execution of Switch are done by statement to statement. No court will be executed in the beginning. PHP only starts the execution of the switch statement when a case statement which matches the switch statement is found. Until the end of dates which block or when it sees a break for the first time PHP will not stop the execution. If there is no break statement at the end of the case statement list, PHP will continue to execute the following case statements.

Example 3:

<?php

switch ($i) {

case 0:

echo "i equals 0";

case 1:

echo "i equals 1";

case 2:

echo "i equals 2";

}

?>

PHP will execute all the statements if $i equals to 0 and will execute the two statements if $1 equals to 1. Only when $i equals to 2, the expected behaviour can be obtained. Thus, the break statements should not be forgotten.

Unlike the if else statement, this with statement will only evaluate the condition once. The obtained result will then be compared to each case statement. In some complicated cases, using the switch instead of else if may be faster.

For a case, the statement list can be empty. In such cases the control will be passed to the next case.

Here is an example where the case is empty.

Example 4:

<?php

switch ($i) {

case 0:

case 1:

case 2:

echo "i is less than 3 but not negative";

break;

case 3:

echo "i is 3";

}

?>

Colon can be used in place of a semicolon after a case.

<?php

switch($beer)

{

case 'tuborg';

case 'carlsberg';

case 'heineken';

echo 'Good choice';

break;

default;

echo 'Please make a new selection...';

break;

}

?>

Break:

Break is used for ending the execution of the current while, do while, for each, for or switch structures. For telling the PHP the number of nested structures which are to be broken out, you can use an optional numeric argument.

Here is an example showing the break and the optional argument

<?php

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');

while (list(, $val) = each($arr)) {

if ($val == 'stop') {

break; /*You could also write 'break 1;' here. */

}

echo "$val<br />\n";

}

/* Using the optional argument. */

$i = 0;

while (++$i) {

switch ($i) {

case 5:

echo "At 5<br />\n";

break 1; /* Exit only the switch. */

case 10:

echo "At 10; quitting<br />\n";

break 2; /* Exit the switch and the while. */

default:

break;

}

}

?>

Example 5

<?php

$favcolor = "red";

switch ($favcolor) {

case "red":

echo "Your favorite color is red!";

break;

case "blue":

echo "Your favorite color is blue!";

break;

case "green":

echo "Your favorite color is green!";

break;

default:

echo "Your favorite color is neither red, blue, or green!";

}

?>

Output: your favourite color is red.

Continue:

In some situations we will have to take the control to the loop's beginning by skipping the remaining statements which are not yet executed. The continue keyword makes it possible. Continue is associated with the if. The control automatically goes back to the beginning of the loop after executing the continue keyword.

Example: here is an example where the odd numbers between 1 to 10 are printed. In the while loop, the numbers are divided by 2 and the reminder of every number is tested. If it returns 0, it is an even number. To avoid the even numbers from being printed, we use the continued statement. With this the control will automatically be passed to the beginning of the loop.

Example:

<?php

$x=1;

echo 'List of odd numbers between 1 to 10 <br />';

while ($x<=10)

{

if (($x % 2)==0)

{

$x++;

continue;

}

else

{

echo $x.'<br />';

$x++;

}

}

Output:

List of odd numbers between 1 to 10

1

3

5

7

9