PHP Unit 1 Flow Control Statements - Part 3
PHP Unit 1 Flow Control Statements - Part 3
PHP supports a number of traditional programming constructs for controlling the flow of execution of a
program.
Conditional statements, such as
if/else and switch, allow a program to execute different pieces of code, or none at all, depending
on some condition.
Loops, such as
while and for, support the repeated execution of particular code.
1. If - Control Statement:
The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a
statement. An if statement looks like:
if (expression)
statement
To specify an alternative statement to execute when the expression is false, use the else keyword:
if (expression)
statement
else
statement
For example:
if ($user_validated)
echo "Welcome!";
else
echo "Access Forbidden!";
To include more than one statement in an if statement, use a block —a curly brace-enclosed set of statements:
if ($user_validated)
{
echo 'Welcome!";
$greeted = 1;
}
else
{
echo "Access Forbidden!";
exit;
}
For example:
if ($user_validated) :
echo "Welcome!";
$greeted = 1;
else :
echo "Access Forbidden!";
exit;
endif;
Other statements also have similar alternate style syntax (and ending keywords); they can be useful if you
have large blocks of HTML inside your statements.
For example:
<?if($user_validated):?>
<table>
<tr>
<td>First Name:</td><td>Sophia</td>
</tr>
<tr>
<td>Last Name:</td><td>Lee</td>
</tr>
</table>
<?else:?>
Please log in.
<?endif?>
if ($good)
print('Dandy!');
else
if ($error)
print('Oh, no!');
else
print("I'm ambivalent...");
Such chains of if statements are common enough that PHP provides an easier syntax: the elseif statement.
if ($good)
print('Dandy!');
elseif ($error)
print('Oh, no!');
else
print("I'm ambivalent...");
The ternary conditional operator (?:) can be used to shorten simple true/false tests.
Take a common situation such as checking to see if a given variable is true and printing something if it is.
With a normal if/else statement, it looks like this:
The main difference here is that the conditional operator is not a statement at all.
This means that it is used on expressions, and the result of a complete ternary expression is itself an
expression.
In the previous example, the echo statement is inside the if condition, while when used with the ternary
operator, it precedes the expression.
The value of a single variable may determine one of a number of different choices (e.g., the variable
holds the username and you want to do something different for each user).
The switch statement is designed for just this situation.
A switch statement is given an expression and compares its value to all cases in the switch;
all statements in a matching case are executed, up to the first break keyword it finds.
If none match, and a default is given, all statements following the default keyword are executed, up to the
first break keyword encountered.
if ($name == 'ktatroe')
// do something
elseif ($name == 'rasmus')
// do something
elseif ($name == 'ricm')
// do something
elseif ($name == 'bobk')
// do something
You can replace that statement with the The alternative syntax for this is: use “:” instead of
following switch statement: “{” curly braces.
switch($name)
{ switch($name):
case 'ktatroe': case 'ktatroe':
// do something // do something
break; break;
case 'rasmus': case 'rasmus':
// do something // do something
break; break;
case 'ricm': case 'ricm':
// do something // do something
break; break;
case 'bobk': case 'bobk':
// do something // do something
break; break;
} endswitch;
Because statements are executed from the matching case label to the next break keyword, you can
combine several cases in a fall-through.
In the following example, "yes" is printed when $name is equal to "sylvie" or to "bruno":
switch ($name)
{
case 'sylvie': // fall-through
case 'bruno':
print('yes');
break;
default:
print('no');
break;
}
Commenting the fact that you are using a fall-through case in a switch is a good idea, so someone doesn't
come along at some point and add a break, thinking you had forgotten it.
The simplest form of loop is the while The alternative syntax for while has this
statement: structure:
If the expression evaluates to true, the statement is executed and then the expression is reevaluated (if it
is true, the body of the loop is executed, and so on).
The loop exits when the expression evaluates to false.
As an example, here's some code that adds the whole numbers from 1 to 10:
$total = 0; $total = 0;
$x = 1; $x = 1;
while ($x <= 10) while ($x <= 10):
{ OR $total += $x;
$total += $x; endwhile;
}
For example: It can prematurely exit a loop with the break keyword. In the following code, $x never reaches a
value of 6, because the loop is stopped once it reaches 5:
$total = 0;
$x = 1;
while ($x <= 10)
{
if ($x == 5)
break; // breaks out of the loop
$total += $x;
$x++;
}
Optionally, can put a number after the break keyword, indicating how many levels of loop structures to
break out of.
In this way, a statement buried deep in nested loops can break out of the outermost loop.
For example:
$x = 0;
while ($x < 10)
{
while ($y < 10)
{
if ($y == 5)
break 2; // breaks out of two while loops
$y++;
}
$x++;
}
echo $x;
echo $y;
Output:
0
5
The continue statement skips ahead to the next test of the loop condition.
As with the break keyword, you can continue through an optional number of levels of loop structure:
PHP also supports a do /while loop, which takes the following form:
do
statement
while (expression)
Use a do/while loop to ensure that the loop body is executed at least once:
$total = 0;
$x = 1;
do
{
$total += $x++;
}
while ($x <= 10);
You can use break and continue statements in a do/while statement just as in a normal while statement.
The do/while statement is sometimes used to break out of a block of code when an error condition occurs.
For example:
do
{
// do some stuff
if ($error_condition)
break;
// do some other stuff
} while (false);
Because the condition for the loop is false, the loop is executed only once, regardless of what happens
inside the loop. However, if an error occurs, the code after the break is not evaluated.
The for statement is similar to the while statement, except it adds counter initialization and counter
manipulation expressions, and is often shorter and easier to read than the equivalent while loop.
Here's a while loop that counts from 0 to 9, printing each number:
$counter = 0;
while ($counter < 10)
{
echo "Counter is $counter\n";
$counter++;
}
The structure of a for statement is: The alternative syntax of a for statement is:
For example:
$total = 0;
for ($i = 0, $j = 0; $i <= 10; $i++, $j *= 2)
{
$total += $j;
}
It can also leave an expression empty, signaling that nothing should be done for that phase.
In the most degenerate form, the for statement becomes an infinite loop.
You probably don't want to run this example, as it never stops printing:
for (;;)
{
echo "Can't stop me!<br />";
}
In for loops, as in while loops, you can use the break and continue keywords to end the loop or the current
iteration.
The declare statement allows you to specify execution directives for a block of code. The structure of
a declare statement is:
declare (directive)
statement
For example:
register_tick_function("some_function");
declare(ticks = 3)
{
for($i = 0; $i < 10; $i++)
{
// do something
}
}