Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1.

Similar presentations


Presentation on theme: "Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1."— Presentation transcript:

1 Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1

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 instruction 2. Selection - a choice of at least two either go to the next instruction or 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 code or continue with the next instruction after the block  Selection and Repetition are called Branching since these are branch points in the flow of control 2

3 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');

4 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.

5 5 Basic PHP Comparison Operators

6 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 true 1  echo false

7 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 true 0.0 === 0 returns false

8 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

9 9 Truth Tables for boolean Operators Value of AValue of BA && B truetruetrue truefalsefalse falsetruefalse falsefalsefalse Value of AValue of BA || B truetruetrue truefalsetrue falsetruetrue falsefalsefalse Value of A!A truefalse falsetrue && (and) || (or) ! (not)

10 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

11 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 switch Branching: Repetition while do-while for foreach

12 12 PHP if statement Syntax: if (Boolean_Expression) Action if true; //execute if true next 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)

13 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 HTML if ($eggsPerBasket < 12) : //begin body of the if statement echo "Less than a dozen..."; $costPerBasket = 1.1 * $costPerBasket; //end body of the if statement endif; $totalEggs = $numberOfEggs * $eggsPerBasket; echo "You have a total of $totalEggs eggs.");

14 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

15 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; }

16 16 Multibranch selection: if-else if-elseif-…-else  One way to handle situations with more than two possibilities  Syntax: if(Boolean_Expression_1) Action_1 elseif(Boolean_Expression_2) Action_2. elseif(Boolean_Expression_n) Action_n else Default_Action

17 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?)

18 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; }

19 19 Iteration  Three different forms of iteration: while for do-while

20 20 While loops  Syntax: while (cond) statement  What it means: Test cond. If false, then while loop is finished; go on to next statement If true, execute statement, then go back and start again Continue like this until cond becomes false or a break is executed.

21 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; }

22 22 Infinite and Empty Loops  while (true); is an infinite loop and you will have to wait a 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);

23 23 While loop examples while (true) echo "I will do the reading assignments"; while (false) echo "I will start my HW early"; Output?

24 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 ”; } echo “I will not execute”;

25 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 ”; } echo “I will always execute”; $x = 5; while ($x++>0) { // skip 3 if($x == 3) continue; echo “$x ”; } echo “I will always execute”;

26 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; } 

27 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; }

28 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.

29 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

30 30 Practical Considerations When 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


Download ppt "Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1."

Similar presentations


Ads by Google