Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Programming– UFCFB Lecture 20

Similar presentations


Presentation on theme: "Web Programming– UFCFB Lecture 20"— Presentation transcript:

1 Web Programming– UFCFB3-30-1 Lecture 20
Instructor : Mazhar H Malik Global College of Engineering and Technology

2 Lecture 21 – PHP Flow Control

3 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

4 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 $grade = 'A'; $age = 10; $year = 'junior'; $is_desired_grade = ($grade == 'A'); $is_driving_age = ($age >= 17); $not_graduating = ($year != 'senior');

5 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 (<, >, <=, >=, ==, ===, !=. !==, …) e.g.: 5 !== 5 return false ( different type). 5 === 5.0 return false (different type). 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 (writing) but can be user-defined via objects and functions. Comparing non-compatible types is legal but may have unexpected results.

6 Basic PHP Comparison Operators

7 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 <no output>

8 "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

9 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 & and | are bitwise operators (allow evaluation and manipulation of specific bits within an integer) && and ||are logical operators

10 Truth Tables for boolean Operators
&& (and) || (or) 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 ! (not)

11 Precedence Rules for Common Operators
Highest Precedence the unary (single) 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

12 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

13 PHP if statement Syntax: if (Boolean_Expression)
Action if true; //execute if true next action; //always executed $numberOfBaskets = 100; $eggsPerBasket = 10; if ($eggsPerBasket < 12) //begin body of the if statement echo "Less than a dozen eggs per basket <br>"; //end body of the if statement $totalEggs = $numberOfBaskets * $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)

14 PHP if statement Syntax: if (Boolean_Expression)
Action if true; //execute if true next action; //always executed $numberOfBaskets = 100; $eggsPerBasket = 10; if ($eggsPerBasket < 12) //begin body of the if statement echo "Less than a dozen eggs per basket <br>"; //end body of the if statement $totalEggs = $numberOfBaskets * $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)

15 PHP Statement Blocks: Compound Statements
Action if(true) is a set of statements enclosed in curly brackets (a compound statement, or block). $numberOfBaskets = 10; $eggsPerBasket = 12; $costPerBasket = 5; if ($eggsPerBasket < 12) { //begin body of the if statement echo "Less than a dozen ... <br>"; $costPerBasket = 1.1 * $costPerBasket; } //end body of the if statement $totalEggs = $numberOfBaskets * $eggsPerBasket; echo "You have a total of $totalEggs eggs. <br>"; echo "price of eggs is ", $numberOfBaskets*$costPerBasket;

16 PHP Statement Blocks: Compound Statements
Action if(true) is a set of statements enclosed in curly brackets (a compound statement, or block). $numberOfBaskets = 10; $eggsPerBasket = 12; $costPerBasket = 5; if ($eggsPerBasket < 12) { //begin body of the if statement echo "Less than a dozen ... <br>"; $costPerBasket = 1.1 * $costPerBasket; } //end body of the if statement $totalEggs = $numberOfBaskets * $eggsPerBasket; echo "You have a total of $totalEggs eggs. <br>"; echo "price of eggs is ", $numberOfBaskets*$costPerBasket;

17 PHP Statement Blocks: Compound Statements
This style is useful when using PHP in large blocks of HTML $numberOfBaskets = 10; $eggsPerBasket = 12; $costPerBasket = 5; if ($eggsPerBasket < 12): //begin body of the if statement echo "Less than a dozen ... <br>"; $costPerBasket = 1.1 * $costPerBasket; endif; //end body of the if statement $totalEggs = $numberOfBaskets * $eggsPerBasket; echo "You have a total of $totalEggs eggs. <br>"; echo "price of eggs is ", $numberOfBaskets*$costPerBasket;

18 PHP Statement Blocks: Compound Statements
This style is useful when using PHP in large blocks of HTML $numberOfBaskets = 10; $eggsPerBasket = 12; $costPerBasket = 5; if ($eggsPerBasket < 12): //begin body of the if statement echo "Less than a dozen ... <br>"; $costPerBasket = 1.1 * $costPerBasket; endif; //end body of the if statement $totalEggs = $numberOfBaskets * $eggsPerBasket; echo "You have a total of $totalEggs eggs. <br>"; echo "price of eggs is ", $numberOfBaskets*$costPerBasket;

19 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

20 if-else Examples Example with single-statement blocks: $time = 10;
$limit = 20; if ($time < $limit) echo "You made it."; else echo "You missed the deadline.";

21 if-else Examples Example with single-statement blocks: $time = 10;
$limit = 20; if ($time < $limit) echo "You made it."; else echo "You missed the deadline.";

22 if-else Examples Example with compound statements: $time = 10;
$limit = 20; if ($time < $limit) { echo "You made it. <br>"; $bonus = 100; } else echo "You missed the deadline. <br>"; $bonus = 0; echo "bonus = ", $bonus;

23 if-else Examples Example with compound statements: $time = 10;
$limit = 20; if ($time < $limit) { echo "You made it. <br>"; $bonus = 100; } else echo "You missed the deadline. <br>"; $bonus = 0; echo "bonus = ", $bonus;

24 Multibranch selection: if-elseif-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

25 if-elseif-elseif-…-else Example
$score = 91; 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'; echo "your grade is ", $grade; Note how the sequence is important here and must use elseif rather than just if (why?) if-elseif-else is more efficient they are NOT functionally equivalent, they will only be equal if you write if statement for every single possible value. The else statement allows you to cover every possible remaining value without having to write millions of if statements . It’s better coding practice to use it just like swtich/case statement.

26 if-elseif-elseif-…-else Example
$score = 91; 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'; echo "your grade is ", $grade; Note how the sequence is important here and must use elseif rather than just if (why?) if-elseif-else is more efficient they are NOT functionally equivalent, they will only be equal if you write if statement for every single possible value. The else statement allows you to cover every possible remaining value without having to write millions of if statements . It’s better coding practice to use it just like swtich/case statement.

27 Use switch for single-variable
$profRel = "friend"; switch($profRel) { case "colleague" : $greeting = "Thomas"; break; case "friend" : $greeting = "Tom"; case "grad student" : $greeting = "TC"; case "undergrad student" : $greeting = "professor"; default : $greeting = "Dr. Collins"; } echo "greeting = ", $greeting;

28 Use switch for single-variable
$profRel = "friend"; switch($profRel) { case "colleague" : $greeting = "Thomas"; break; case "friend" : $greeting = "Tom"; case "grad student" : $greeting = "TC"; case "undergrad student" : $greeting = "professor"; default : $greeting = "Dr. Collins"; } echo "greeting = ", $greeting;

29 Iteration Three different forms of iteration: while for do-while

30 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 condition becomes false or a break is executed.

31 While loop Examples $x = 5; $s = 0; while ($x > 0) { $s = $s + $x;
$x = $x-1; echo "s = ", $s, "<br>"; echo "x = ", $x, "<br>"; }

32 While loop Examples $x = 5; $s = 0; while ($x > 0) { $s = $s + $x;
$x = $x-1; echo "s = ", $s, "<br>"; echo "x = ", $x, "<br>"; }

33 While loop Examples $s = 0; $x = 1; while ($x <= 5) { $s = $s + $x;
$x = $x + 1; echo "s = ", $s, "<br>"; echo "x = ", $x, "<br>"; }

34 While loop Examples $s = 0; $x = 1; while ($x <= 5) { $s = $s + $x;
$x = $x + 1; echo "s = ", $s, "<br>"; echo "x = ", $x, "<br>"; }

35 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 Checking that the initial condition is true Checking that the loop condition will eventually change to false Do NOT EVER use ; after while() 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);

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

37 The exit Function $x = 1; while ($x++>0) {
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 = 1; while ($x++>0) { // terminate program at 3 if($x == 3) die("done!"); echo "$x<br>"; } echo "I will not execute";

38 The exit Function $x = 1; while ($x++>0) {
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 = 1; while ($x++>0) { // terminate program at 3 if($x == 3) die("done!"); echo "$x<br>"; } echo "I will not execute";

39 break If you have a situation where need to exit the loop but not terminate the program use break. $x = 1; while ($x++<10) { // stop early at 6 if($x == 6) break; echo "$x<br>"; }

40 break If you have a situation where need to exit the loop but not terminate the program use break. $x = 1; while ($x++<10) { // stop early at 6 if($x == 6) break; echo "$x<br>"; }

41 continue 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 = 1; while ($x++<10) { // stop early at 6 if($x == 6) continue; echo "$x<br>"; }

42 continue 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 = 1; while ($x++<10) { // stop early at 6 if($x == 6) continue; echo "$x<br>"; }

43 for loops Convenient syntax for loops with loop variables that are incremented or decremented each time through the loop (as in previous examples). Recall: init; while (cond) { statement incr; } for (init; cond; incr) statement;

44 for loop examples  $s = 0; for ($x = 5; $x > 0; $x = $x-1) {
$s = $s + $x; echo "s = ", $s, "<br>"; } $s = 0; $x = 5; while ($x > 0) { $s = $s + $x; $x = $x-1; echo "s = ", $s, "<br>"; }

45 for loop examples  $s = 0; for ($x = 5; $x > 0; $x = $x-1) {
$s = $s + $x; echo "s = ", $s, "<br>"; } $s = 0; $x = 5; while ($x > 0) { $s = $s + $x; $x = $x-1; echo "s = ", $s, "<br>"; }

46 for loop examples  $s = 0; for ($x = 1; $x <= 10; $x = $x+1) {
$s = $s + $x; echo "s = ", $s, "<br>"; }; $s = 0; $x = 1; while ($x <= 10) { $s = $s + $x; $x = $x + 1; echo "s = ", $s, "<br>"; }

47 for loop examples  $s = 0; for ($x = 1; $x <= 10; $x = $x+1) {
$s = $s + $x; echo "s = ", $s, "<br>"; }; $s = 0; $x = 1; while ($x <= 10) { $s = $s + $x; $x = $x + 1; echo "s = ", $s, "<br>"; }

48 for loop usage executes statement exactly n times.
One use of for loops is simply to execute a statement, or sequence of statements, a fixed number of times: for ($i = 1; $i <= n; $i++) statement executes statement exactly n times.

49 for loop usage Example: print "I will not turn HW in late" a hundred times. for ($i = 1; $i <= 100; $i++) echo "I will not turn HW in late"); 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 = 0; $i < 20; $i++) { if ($i%2 == 1) //if i is odd echo "My robot loves me\n"; else //if i is even echo "My robot loves me not\n"; } for ($i = 1; $i <= 20; $i++) { echo "\nMy robot loves me"; if ($i%2 == 0) echo " not"; } OR

50 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 (OBOE) is a logic error involving the discrete equivalent of a boundary condition. It often occurs in computer programming when an iterative loop iterates one time too many or too few. This problem could arise when a programmer makes mistakes such as using "is less than or equal to" where "is less than" should have been used in a comparison 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 be tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one and other possible errors


Download ppt "Web Programming– UFCFB Lecture 20"

Similar presentations


Ads by Google