lecture 4 – php flow control sfdv3011 – advanced web development 1
TRANSCRIPT
![Page 1: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/1.jpg)
1
Lecture 4 – PHP Flow Control
SFDV3011 – Advanced Web Development
![Page 2: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/2.jpg)
2
What is "Flow of Control"? Flow of Control is the execution order of instructions in a
program
All programs can be written with three control flow elements:
1. Sequence - just go to the next instruction2. Selection - a choice of at least two
either go to the next instructionor jump to some other instruction
3. Repetition - a loop (repeat a block of code) at the end of the loop
either go back and repeat the block of codeor continue with the next instruction after the block
Selection and Repetition are called Branching since these are branch points in the flow of control
![Page 3: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/3.jpg)
3
The Type boolean A primitive type
Can have expressions, values, constants, and variables just as with any other primitive type
Only two values: true and false
Every expression is boolean in some way• 0, 0.0, '0', '' are all false• Anything other than the above is true
Comparison operators always return boolean
$is_desired_grade = ($grade == 'A');$is_driving_age = ($age >= 17);$not_graduating = ($year != 'senior');
![Page 4: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/4.jpg)
4
Boolean Expressions Boolean expressions can be thought of as test conditions
(questions) that are either true or false Often two values (numbers, strings) are compared, return
value is a boolean (i.e. true or false)For example:Is A greater than B?, Is A equal to B?, Is A less than or equal to B?
Comparison operators are used for boolean expressions(<, >, <=, >=, ==, ===, !=. !==, …)
A and B can be any data type (or class), but they generally are a "compatible" data type (or class)• Comparisons are either numeric or lexicographic but can
be user-defined via objects and functions.• Comparing non-compatible types is legal but may have
unexpected results.
![Page 5: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/5.jpg)
5
Basic PHP Comparison Operators
Math Notation
Name
PHP Notation
PHP Examples
= equal to == $balance == 0 $answer == 'y'
not equal to != $income != tax $answer != 'y'
> greater than
> $income > $outgo
greater than or equal to
>= $points >= 60
< less than
< $pressure < $max
less than or equal to <= $income <= $outgo
![Page 6: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/6.jpg)
6
A Note on Printing Boolean Values
The echo (and print) command will convert values to strings for printing• true is converted to '1'• false is converted to “” (the empty string)
echo true1
echo false<no output>
![Page 7: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/7.jpg)
7
"Identical" Comparison Operators Sometimes you really want to be sure two values are
exactly the same value and type
Is 0.0 equal to 0?
Use the '===' and '!==' to test equality and non-equality for both value and type
0.0 == 0 returns true0.0 === 0 returns false
![Page 8: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/8.jpg)
8
Compound Boolean Expressions
Use && or and to AND (intersect) two or more conditions
Use || to OR (union) two or more conditions
For example, write a test to see if B is either 0 or between the values of A and C :(B == 0) || (A <= B && B < C)(B == 0) or (A <= B) and B < C)
In this example the parentheses are not required but are added for clarity• Subject to Precedence rules• Use a single & for AND and a single | for OR to avoid short-
circuit evaluation and force complete evaluation of an expression
![Page 9: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/9.jpg)
9
Truth Tables for boolean Operators
Value of A Value of B A && B
true true true
true false false
false true false
false false false
Value of A Value of B A || B
true true true
true false true
false true true
false false false
Value of A !A
true false
false true
&& (and) || (or)
! (not)
![Page 10: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/10.jpg)
10
Precedence Rules for Common Operators
Highest Precedence• the unary operators: ++, --, and !• the binary arithmetic operators: *, /, %• the binary arithmetic operators: +, -• the boolean operators: <, >, =<, >=• the boolean operators: ==, !=• the boolean operator &• the boolean operator |• the boolean operator &&• the boolean operator ||
Lowest Precedence
![Page 11: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/11.jpg)
11
PHP Flow Control Statements
Sequential• the default• PHP automatically
executes the next instruction unless you use a branching statement
Branching: Selection• if• if-else• if-else if-else if- … - else• switchBranching: Repetition• while• do-while• for• foreach
![Page 12: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/12.jpg)
12
PHP if statementSyntax:
if (Boolean_Expression) Action if true; //execute if truenext action; //always executed
if ($eggsPerBasket < 12) //begin body of the if statement echo "Less than a dozen eggs per basket"; //end body of the if statement$totalEggs = $numberOfEggs * $eggsPerBasket;echo "You have a total of $totalEggs eggs.";
The body of the if statement is conditionally executed
Statements after the body of the if statement always execute (not conditional unless grouped inside {}'s)
![Page 13: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/13.jpg)
13
PHP Statement Blocks:Compound Statements
Action if(true) is a set of statements enclosed in curly brackets (a compound statement, or block).
if ($eggsPerBasket < 12){ //begin body of the if statement echo "Less than a dozen ..."; $costPerBasket = 1.1 * $costPerBasket;} //end body of the if statement$totalEggs = $numberOfEggs * $eggsPerBasket;echo "You have a total of $totalEggs eggs."); This style is useful when using PHP in large blocks of
HTMLif ($eggsPerBasket < 12) ://begin body of the if statement echo "Less than a dozen ..."; $costPerBasket = 1.1 * $costPerBasket;//end body of the if statementendif;$totalEggs = $numberOfEggs * $eggsPerBasket;echo "You have a total of $totalEggs eggs.");
![Page 14: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/14.jpg)
14
Two-way Selection: if-else Select either one of two options Either do Action1 or Action2, depending on test value
Syntax:if (Boolean_Expression){ Action1 //execute only if Boolean_Expression true}else{
Action2 //execute only if Boolean_Expression false}
Action3 //anything here always executed
![Page 15: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/15.jpg)
15
if-else Examples Example with single-statement blocks:
if ($time < $limit) echo "You made it.";else echo "You missed the deadline.";
Example with compound statements:
if ($time < $limit){ echo "You made it."; $bonus = 100;}else{ echo "You missed the deadline."; $bonus = 0;}
![Page 16: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/16.jpg)
16
Multibranch selection:if-else if-elseif-…-else
One way to handle situations with more than two possibilities
Syntax:if(Boolean_Expression_1) Action_1elseif(Boolean_Expression_2) Action_2 . . .elseif(Boolean_Expression_n) Action_nelse Default_Action
![Page 17: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/17.jpg)
17
if-elseif-elseif-…-else Example
if($score >= 90 && $score <= 100) $grade= 'A';elseif ($score >= 80) $grade= 'B';elseif ($score >= 70) $grade= 'C';elseif ($score >= 60) $grade= 'D';else $grade= 'E';
Note how the sequence is important here and must use elseif rather than just if (why?)
![Page 18: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/18.jpg)
18
Use switch for single-variable
switch($profRel) {case "colleague" :
$greeting = "Thomas";break;
case "friend" : $greeting = "Tom";
break;case "grad student" :
$greeting = "TC";break;
case "undergrad student" : $greeting = "professor";
break;default :
$greeting = "Dr. Collins";break;
}
![Page 19: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/19.jpg)
19
Iteration
Three different forms of iteration:• while• for• do-while
![Page 20: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/20.jpg)
20
While loops
Syntax: while (cond) statement
What it means: Test cond.
If false, then while loop is finished; go on to next statementIf true, execute statement, then go back and start again
Continue like this until cond becomes false or a break is executed.
![Page 21: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/21.jpg)
21
While loop Examples
$x = 5;$s = 0;while ($x > 0) { $s = $s + $x; $x = $x-1;}
$s = 0; $x = 1;while ($x <= 10) { $s = $s + $x; $x = $x + 1;}
![Page 22: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/22.jpg)
22
Infinite and Empty Loops while (true); is an infinite loop and you will have to waita long time!
while (false){//stuff} and while ($n++ < 10); {//stuff} are empty loops and will never execute anything
You should take care to ensure your loop is good by
(1) Checking that the initial condition is true(2) Checking that the loop condition will eventually change
to false(3) Do NOT EVER use ; after while()(4) Make sure you initialize loop variables BEFORE the loop
Generally PHP has a maximum execution time to help avoid crashing the system (default 60 secs).
You can set this to a lower value such as 5 sec by using set_time_limit (5);
![Page 23: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/23.jpg)
23
While loop examples
while (true)echo "I will do the reading assignments";
while (false) echo "I will start my HW early";
Output?
Output?
![Page 24: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/24.jpg)
24
The exit Function If you have a situation where it is pointless to continue
execution you can terminate the program with the exit() or die() functions
A string is often used as an argument to identify if the program ended normally or abnormally
$x = 5;while ($x++>0) {// terminate program at 3 if($x == 3) die(“done!”); echo “$x<br>”;}echo “I will not execute”;
![Page 25: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/25.jpg)
25
break and continue If you have a situation where need to exit the loop but not
terminate the program use break
If want to stop executing the statements in the loop for a given cycle and immediately jump to the top of the loop to start the next cycle use continue
$x = 5;while ($x++>0) {// stop early at 3 if($x == 3) break; echo “$x<br>”;}echo “I will always execute”;
$x = 5;while ($x++>0) {// skip 3 if($x == 3) continue; echo “$x<br>”;}echo “I will always execute”;
![Page 26: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/26.jpg)
26
for loops
Convenient syntax for loops with loop variables that are incremented or decremented each time through the loop (as in previous examples).
Recall:
for (init; cond; incr) statement
init;while (cond) { statement incr;}
![Page 27: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/27.jpg)
27
for loop examples$s = 0; $x = 5;while ($x > 0) { $s = $s + $x; $x = $x-1;}
$s = 0; for ($x = 5; $x > 0; $x = $x-1) $s = $s + $x;
$s = 0; for ($x = 1; $x <= 10; $x = $x+1) $s = $s + $x;
$s = 0; $x = 1;while ($x <= 10) { $s = $s + $x; $x = $x + 1;}
![Page 28: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/28.jpg)
28
for loop usage
for ($i = 1; $i <= n; $i++) statement
One use of for loops is simply to execute a statement, or sequence of statements, a fixed number of times:
executes statement exactly n times.
![Page 29: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/29.jpg)
29
for loop usage
for ($i = 1; $i <= 100; $i++) echo "I will not turn HW in late");
Example: print "I will not turn HW in late" a hundred times.
for ($i = 0; $i < 20; $i++) { if ($i%2 == 1)
echo "My robot loves me\n"; else echo "My robot loves me not\n";}
Loop bodies can be as complicated as you like. This loop prints:
"My robot loves me" and "My robot loves me not" on alternate lines, ten times each:
for ($i = 1; $i <= 20; $i++) { echo "\nMy robot loves me"; if ($i%2 == 0) echo " not"; }
OR
![Page 30: Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1](https://reader036.vdocuments.site/reader036/viewer/2022070400/56649f0e5503460f94c22ff4/html5/thumbnails/30.jpg)
30
Practical ConsiderationsWhen Using Loops
The most common loop errors are unintended infinite loops and off-by-one errors in counting loops
An off-by-one error is an error that occurs when a loop is executed one too many or one too few times.
Sooner or later everyone writes an unintentional infinite loop (To get out of an unintended infinite loop enter ^C (control-C) or stop button on browser)
Loops should tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors