230 likes | 262 Views
Learn about the flow of control in programming, including sequence, selection, and repetition. Understand PHP if statements, boolean expressions, and comparison operators. Master PHP flow control statements for better program execution.
E N D
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
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 PHP Flow Control Statements
PHP if statement • Simple decisions • Do the next statement if test is true or skip it if false • Syntax: if (Boolean_Expression) Action if true; //execute if true next action; //always executed • Note the indentation for readability (not compiler or execution correctness)
if Example 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
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_drinking_age = ($age >= 21); $not_graduating = ($year != 'senior');
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.
Note: 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>
"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
Compound Boolean Expressions • Use && 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) • In this example the parentheses are not required but are added for clarity • Subject to Precedence rules
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
PHP Statement Blocks:Compound Statements • Action if(true) can be either a single statement or a set of statements enclosed in curly brackets (a compound statement, or block). For example: All statements between braces are controlled by if 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.");
PHP Statement Blocks:Compound Statements Alternatively, "if(<exp>):… endif; " also works: All statements between : and endif; are controlled by if 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."); • This style is useful when using PHP in large blocks of HTML.
Gotchas - 1 • Statements after the body of the if statement always execute (not conditional unless grouped inside {}'s) • Let's say you want to give free shipping and a 10% discount if the order is $50: Wrong: if ($total > 50) $shipping = 0; $total = $total *0.9; Right: if ($total > 50) { $shipping = 0; $total = $total *0.9; }
Gotchas - 2 • Never put a ; after the if statement! • What will be the values of $total and $shipping after the if test below? • Why? $total = 40; $shipping=10; if ($total > 50); { $shipping = 0; $total = $total *0.9; }
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 //code here is always executed
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; }
Multibranch selection:if-else if-elseif-…-else • If you have more than two conditions… • Syntax: if(Boolean_Expression_1) { Action_1 } elseif(Boolean_Expression_2) { Action_2 } . . . elseif(Boolean_Expression_n) { Action_n } else { Default_Action }
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= ‘F'; } • Note how the sequence is important here and must use elseif rather than just if (why?)
if-elseif-elseif-…-elseExample 2 if ($profRel == "colleague") { $greeting = "Thomas"; } elseif ($profRel == "friend") { $greeting = "Tom"; } elseif ($profRel == "grad student") { $greeting = "TC"; } elseif ($profRel == "undergrad student") { $greeting = "professor";} else { $greeting = "Dr. Collins";}
Better: use switch for single-variable if 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; }
Use switch when there are many possible matches $year = 2019; switch ($year % 12) { case 0: $yearname = 'Monkey'; break; case 1: $yearname = 'Rooster'; break; case 2: $yearname = 'Dog'; break; case 3: $yearname = 'Boar'; break; case 4: $yearname = 'Rat'; break; case 5: $yearname = 'Ox'; break; case 6: $yearname = 'Tiger'; break; case 7: $yearname = 'Rabbit'; break; case 8: $yearname ='Dragon'; break; case 9: $yearname = 'Snake'; break; case 10: $yearname = 'Horse'; break; case 11: $yearname = 'Lamb'; break; } echo "Year $year is a $yearname";