0 0
Read Time:14 Minute, 55 Second

FREE php course Lecture #5: Selection Structure  Any PHP script is built out of a series of statements. A statement can be an assignment, a function call,
a loop (discussed in a later lecture), a conditional statement, or even a statement that does nothing (an
empty statement). Statements usually end with a semicolon. In addition, statements can be grouped
into a statement-group by encapsulating a group of statements with curly braces. A statement-group is
a statement by itself as well.

Control Statements … FREE php course

A control statement is a statement that is used to alter the continuous sequential invocation of
statements. It is a statement that controls when and how one or more other statements are executed. In
PHP, statements fall into three general types:

Assignment, where values, usually the results of calculations, are stored in variables (as discussed
in previous lecture).
Input / Output, data is read in or printed out.
Control, the program makes a decision about what to do next.

Unless being specified, statements in a PHP program are executed one after another in the order in
which they are written, this is known as sequential execution. However, programs can be much more
useful if the programmer can control the sequence in which statements are run. You will soon find out
that there will always be a need to jump off the linear sequence. A transfer of control occurs when the
next statement to be executed are specified by the programmer, instead of the immediate succeeding
statement.

As a programmer, the control of statement sequence is actually the arrangement of:

• selecting between optional sections of a program.
• repeating important sections of the program.

All PHP programs are thus written in terms of three forms of control: sequence, selection, and
repetition.

Conditional Statements

A conditional statement is used to decide whether to do something at a special point or to decide
between two courses of action. A conditional statement chooses among alternative actions in a PHP
program. The if statement performs (selects) an action based on a tested condition.

A condition is an expression with a Boolean value (TRUE or FALSE) that is used for decision making. For example,

$x >= 3

In this statement, the value of variable $x can be anything, such as 1, 2, 8, 110, 224, and so on. This
expression is then sometimes true, sometime false depending on the current value of $x .

Conditional statements can be as simple as the above one or they can be compound statements as
shown below:

($x >= 3) AND ($x <= 15)

For example:

<?php
$s = 6;
$t = 5;
if ($s>4 AND $t>4) {echo “TRUE!”; }
?>

The output is TRUE! because both conditions $s>4 and $t>4 are true.

 

The if statement …..,, FREE php course

The if statement is one of the most important features of many languages, PHP included. It allows for
conditional execution of code fragments. PHP’s if statement is similar to that of the C programming
language.

In PHP, many conditional statements (also known as selection statements) begin with the keyword if,
followed by a condition in parentheses.

The statement(s) of execution are grouped together between curly brackets { }. Such a grouping is called a compound statement or simply a block. The syntax
then looks like:

if ( condition )
{ execution }

where condition is an expression that is evaluated to its Boolean value. If expression evaluates to
TRUE, PHP will execute the statement, and if it evaluates to FALSE, PHP ignores it.
The following test decides whether a student has passed an exam with a passing mark of 60. Notice
that it is possible to use the if part without the else part.

<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 60) // test if the value of user entry >= 60
{ echo “Pass!”; } // display Pass!
?>

The following example checks whether the current value of the variable $hour is less than 12 and the
echo statement displays its message only if this is the case (namely $hour < 12 is true).

<?php
$hour = date(“H”); //get the current hour value
if ($hour < 12) {
echo “Good morning!”;
}
?>

The if … else statement

The above example has a logic problem. It specifies what to execute when the $grade is greater than or
equal to 60, but it did not specify what to do if the $grade is less than 60. To solve this logic problem,
use the if … else statement. The if statement performs an indicated action (or sequence of actions) only
when the condition is tested to be true; otherwise the execution is skipped. The if … else statement
performs an action if a condition is true and performs a different action if the condition is false.
The else statement extends an if statement to execute a statement in case the expression in the if
statement evaluates to FALSE. The syntax looks like:

if ( condition )
{ execution 1 } // do this when condition is TRUE
else
{ execution 2 } // do this when condition is FALSE

You can now rewrite the above example to:

<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 60) // condition
{ echo “Pass!”; } // execution 1
else
{ echo “Fail!”; } // execution 2
?>

 

The else statement is only executed if the “if” expression is evaluated to FALSE as well as any elseif
expressions that evaluated to FALSE.

Often you need to have more than one statement to be executed conditionally. Of course, there is no
need to wrap each statement with an if clause. Instead, you can group several statements into a
statement group.

If statements can be nested infinitely within other if statements, which provides you with complete
flexibility for conditional execution of the various parts of your program.

The elseif statement ….. FREE php course

Sometimes a programmer needs to make a decision based on several conditions. This can be done by
using the elseif variant of the if statement.

The elseif statement, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if
expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if
the elseif conditional expression evaluates to TRUE.

As soon as one of these conditions yields a true result, the following statement or block is executed and
no further comparisons are performed.

There may be several elseif’s within the same if statement. The first elseif expression (if any) that
evaluates to TRUE would be executed. In PHP, you can also write else if (in two words) and the
behavior would be identical to the one of elseif (in a single word). The syntactic meaning is slightly
different, but the bottom line is that both would result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression and any preceding elseif
expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

In the following example we are awarding grades depending on the exam result.

<?php
$grade=rand(50,99); // generate a random number from 50 to 99
if ($grade >= 90)
{ echo “A”; }
elseif ($grade >= 80)
{ echo “B”; }
elseif ($grade >= 70)
{ echo “C”; }
elseif ($grade >= 60)
{ echo “D”; }
else
{ echo “F”; }
?>

In this example, all comparisons test a single variable called result. In other cases, each test may
involve a different variable or some combination of tests. The same pattern can be used with more or
fewer elseif’s, and the final lone “else” may be left out. It is up to the programmer to devise the correct
structure for each programming problem.

The if…then statement can also be used to handle HTML form in one single PHP script (a later lecture
will discuss this topic in details). For example:

<?php
if ($_POST) { // if the form is filled out
$x = $_POST[“vofx”];
if ($x>=5) { echo “x is greater than or equal to 5!”; }

else { echo “x is less than 5!”; }
}
else { // otherwise display the form
?>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”>
Enter a value for <i>x</i>:
<input type=”text” name=”vofx” size=5>
<input type=”submit” value=”Check”></form></p>
<?php
}
?>

The $_POST expression is evaluated when the script is loaded to determine whether or not the form
fields (a textbox) has been filled in. If so, the script ignores the else part and processes the user input. If
not, the script displays only a form for the user to fill in.

if ($_POST) { // if the form is filled out
…… }
else { // otherwise display the form
?>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”>
……
</form>
<?php
}
?>

Notice that it uses the $_SERVER[‘PHP_SELF’] system variable to send the user inputs to itself.

Alternative syntax ….. FREE php course

PHP offers an alternative syntax for some of its control structures. the basic form of the alternate
syntax is to change the opening brace to a colon (:) and the closing brace to endif. For example:

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block “A is equal to 5″ is nested within an if statement written in the
alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and
else in the alternative format.

<?php
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;

?>

Note that elseif and else … if will only be considered exactly the same when using curly brackets as in
the above example. When using a colon to define your if/elseif conditions, you must not separate else if
into two words or PHP will fail with a parse error.

Problem of complexity

When writing a PHP program, you may have to compare the same variable (or expression) with many
different values, and execute a different piece of code depending on which value it equals to. You can
do so with nested if … else statements, but it will increase the complexity of your program. Consider
the following example:

<?php
$x= date(“w”); //number of the day of the week; 0 for Sunday
if ($x == 0) { echo “Sunday”; }
elseif ($x == 1) { echo “Monday”; }
elseif ($x == 2) { echo “Tuesday”; }
elseif ($x == 3) { echo “Wednesday”; }
elseif ($x == 4) { echo “Thursday”; }
elseif ($x == 5) { echo “Friday”; }
elseif ($x == 6) { echo “Saturday”; }
else { echo “No such option!”; }
?>

This above code will display different value according to the number of the weekday—0 for Sunday, 1
for Monday, and so on. If the number is not in {0, 1, 2, 3, 4, 5, 6}, then it will display “No such
option!”. This example use only one block of code to handle 8 conditions, which certainly increase the
complexity (imaging you have 20 conditions!). This is exactly what the switch statement is for.

The switch..case Statement

The switch statement is similar to a series of if statements on the same expression, but it is a better way
of writing a program when a series of if..else’s occurs. It is important to understand how the switch
statement is executed in order to avoid mistakes. The switch statement executes line by line (actually,
statement by statement). The switch/case statement syntax is as follows:

switch (expression) {
case value1:
statement(s);
break;
case value2:
statement(s);
break;
………..
………..
default:
statement(s);
break;
}

where the case expression may be any expression that evaluates to a simple type, that is, integer or
floating-point numbers and strings. Arrays or objects cannot be used here unless they are not
referenced to a simple type.

In a switch statement, the condition is evaluated only once and the result is compared to each case
statement. In an elseif statement, the condition is evaluated again. If your condition is more
complicated than a simple compare and/or is in a tight loop, a switch may be faster. The advantage of
using switch statement is to simplify the complexity of if…else’s.

The following two examples show two different ways to test for the same conditions – one uses a series
of if and elseif statements, and the other uses the switch statement.

It is important to understand how the switch statement is executed in order to avoid mistakes. The
switch statement executes line by line (actually, statement by statement). In the beginning, no code is
executed. Only when a case statement is found with a value that matches the value of the switch
expression does PHP begin to execute the statements. PHP continues to execute the statements until
the end of the switch block or the first time it sees a break statement. The break construct is used to
force the switch code to stop. PHP will continue to execute the statements until the end of the switch
block or the first time it sees a break statement. If you don’t include a break statement at the end of a
case’s statement list, PHP will go on executing the statements of the following case.

Consider the following examples;

FREE php course
FREE php course

Only when a case statement is found with a value that matches the value of the switch expression does
PHP begin to execute the switch statements.

Notice that a special case is the default case. This case matches anything that doesn’t match any other
cases, and should be the last case statement.

In PHP, the statement list for a case can also be empty, which simply passes control into the statement
list for the next case. The use of default case is also optional. In the following example, only when the
weekday is Tuesday will a user see an output.

 

<?php
$i= date(“w”);
switch ($i) {
case 0:
case 1:
case 2:
echo “It is Tuesday, and you just won the prize!”;
break;
case 3:
case 4:
case 5:
case 6:
}
?>

In PHP, the switch structure allows usage of strings. For example,

<?php
switch ($i) {
case “apple“:
echo “i is apple”;
break;
case “bar“:
echo “i is bar”;
break;
case “cake“:
echo “i is cake”;
break;
}
?>

The alternative syntax for control structures is supported with switches. For example:

<?php
switch ($i):
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i is not equal to 0, 1 or 2”;
endswitch;
?>

It is possible to use a semicolon ( ; )instead of a colon ( : )after a case. For example:
<?php
switch($beer)
{
case ‘Tuborg’;
case ‘Carlsberg’;
case ‘Heineken’;
echo ‘Good choice’;
break;
default;
echo ‘Please make a new selection…’;
break;

}
?>

 

Review Questions

1. The result of the following calculation is __.

<?php echo (9 != 7); ?>

A. 1
B. 0
C. True
D. False

2. The result of the following calculation is __.

<?php echo !(6 <= 4); ?>

A. 1
B. 0
C. True
D. False

3. Given the following code segment, what is the output?

<?php
$x = 3;
if ($x > 3) { echo “Correct!”; }
else { echo “Incorrect!”; }
?>

A. Correct!
B. Incorrect!
C. True
D. False

4. Given the following code segment, what is the output?

<?php
$x = 6;
if (($x > 3) AND ($x <=7)) { echo “Correct!”; }
else { echo “Incorrect!”; }

?>

A. Correct!
B. Incorrect!
C. True
D. False

5. The result of the following calculation is __.

<?php
$i=6;
if ($i>=4) {
if ($i=5) { echo $i; }
else { echo $i–;} }
else { echo $i++; }
?>

A. 4
B. 5

C. 6
D. 3

6. The result of the following calculation is __.

<?php
$i=3;
if ($i>=4) {
if ($i=5) { echo $i; }
else { echo $i–; } }
else { echo ++$i; }
?>

A. 4
B. 5
C. 6
D. 3

7. If the value of $i is 0, what is output?

<?php
switch ($i) {
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i equals 3”;
break;
}
?>

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3

8. If the value of $i is 3, what is output?

<?php

switch ($i) {
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i equals 3”;
break;
}
?>

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3

9. If the value of $i is 7, what is output?

<?php
switch ($i) {
case 0:
echo “i equals 0”;
break;
case 1:
echo “i equals 1”;
break;
case 2:
echo “i equals 2”;
break;
default:
echo “i equals 3”;
break;
}
?>

A. i equals 0
B. i equals 1
C. i equals 2
D. i equals 3

10. If the value of $i is 0, what is output?

<?php
switch ($i) {
case 0: echo “i equals 0”;
case 1: echo “i equals 1”;
case 2: echo “i equals 2”;
default: echo “i equals 3”;
}
?>

A. i equals 0
B. i equals 0i equals 1
C. i equals 0i equals 1i equals 2
D. i equals 0i equals 1i equals 2i equals 3

full lectures HERE

FREE php course

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
FREE php course Previous post free PHP programming course E4 learn to code
Overloading in Java Next post What Is Overloading in Java?

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

Close