Web Programming PHP flow of control & functions COM427 1 Program Control • To date all program flow has been sequential (in program line sequence) • Other control mechanisms are required for more complex programs: – Alternative pathways depending on conditional values (if statements, switch statements) – Repeated instructions (for loops, while loops) – Creating program functions which can be defined and used multiple times COM427 2 Alternative pathways • Conditions can be tested to allow different pathways of instructions to be followed (if statement) • For example textbox input values can be checked to see: – If any value has been entered (blank?) & if so an entry can be requested – If the correct type of value has been entered (numeric?) & if not a correct value can be requested – Otherwise (i.e. non-blank, correct type of data) so process value COM427 3 Conditional Test Statement • if statement – elseif clause (alternative if) – else clause (default where no if… else if true) • Switch statement – Used for large number of conditions COM427 4 If statement If a condition is true then some consequence follows General Format If (condition) statement; If (condition) { statement; // consequence of a true condition ………….. } COM427 5 If…elseif….else • Where there series of alternative conditions we need else if clauses and also a default action if none of the conditions are true if (condition is true) then ……. else if (alternative condition is true) then….. else if (another alternative condition is true) then …. ………………………………………………… else do this (no condition required) COM427 6 If …. ElseIf General Format if (condition) { statement; } elseif (condition) { statement; } else statement; COM427 7 Condition Checking • Conditions are placed inside round brackets • Conditions are either true (causing statements to be executed and no further alternative conditions are considered) or false (causing next alternative to be considered) • They are often formulated as a variable compared to a value or other variable, but can be a function which evaluated to true or false [e.g. is_numeric( variable) ] • Note particularly that for a condition is equal to is == (and NOT just = ) COM427 8 Comparison Operators Test Effect Operator == Equal to Example Result if ($x == 6){ $x = $y + 1; $y = $x + 1; } Run the second and third statements if the value of $x is equal to 6. != Not equal to if ($x != $y) { $x = 5 + 1; } Run the second statement if the value of $x is not equal to the value of $y. < Less than if ($x < 100) { $y = 5; } Run the second statement if the value of $x is less than 100. COM427 9 Comparison Operators (2) Test Effect Operator Example Result Run the second statement if the value of $x is greater than 51. > Greater than if ($x > 51) { print "OK"; } >= Greater than or equal to if (16 >= $x) { Run the second statement if 16 is print "x=$x"; greater than or equal to the value of } $x. <= Less than if ($x <= $y) { Run the second and third statements print "y=$y"; if the value of $x is less than or or equal to print "x=$x"; equal to the value of $y. } COM427 10 If example <?php $destination= "Mexico"; if ($destination== "Iceland") { print "Remember to pack a woolly jumper"; } elseif ($destination== "Mexico") { print "Remember to pack sun cream"; } else print "Stay at home"; // default result ?> COM427 11 Exercise 1 – to try • Adapt the previous If example to work out interest in a savings account – Assign an initial amount to the account and print it – If the amount is 0 then • Print your account is empty – Else If the amount is at less than 100 (£) then • Add 1% interest to the amount • Print the new overall amount – Else If the amount is at least 100 (£) then • Add 2% to the amount • Print the new overall amount COM427 12 Using multiple conditions • When using more than one condition the logical AND & OR is required • In PHP AND is && and BOTH conditions must be true • In PHP OR is II and EITHER condition must be true • Negation is ! • If x is greater than 10 but less than 20 is expressed as If ($x > 10 && $x < 20) { ………. } • If y is less than 50 or above 100 is expressed as If ($y < 50 || $y > 100) { COM427 ………. } 13 Switch Statement (multiple if….. elseif..) General Format switch (expression) { Case "value 1": statement; break; Case "value 2": statement; break; Default: statement; } COM427 14 Switch example <?php $destination = "Mexico"; Switch ($destination) { case "Mexico": print "Remember to pack sun cream"; break; case "Iceland": print "Remember to pack a woolly jumper"; break; Default: Print "Stay at home"; } ?> COM427 15 Example – age group survey • Problem: Design a simple age group survey, using an HTML form to collect the age and using PHP to return the following message: – if the participant is younger than 18 display "You're young – enjoy it!"; – if the participant is older than 18 and less than 50 display "You're in the prime of your life"; – If the participant is older than 50 display "You can retire soon – hurrah!" – Display other relevant message if you wish age_front.html age_back.php COM427 16 age_front.html <html><body> Age Survey Form<br /><br /> <form action="age_back.php" method="post"> Enter Your Age<input type="text" name="age"><br /><br /> <input type="submit" value="Click To Submit"> </form> </body></html> COM427 17 age_back.php <?php print "Thank you for taking the survey!<br /><br />\n"; $Age = $_POST["age"]; // receive posted age from textbox if ($Age < 18) { print ("You're young – enjoy it!<br />\n"); } elseif ($Age >= 18 && $Age < 50) { print "You're in the prime of your life! <br />"; } elseif ($Age >= 50) { print "You can retire soon – hurrah! <br />"; } else { print "number not a positive number"; } ?> COM427 18 Exercise 2 – to try if (condition) { statement; } elseif (condition) { statement; } else statement; Create a php program to check the stock level - Assume that an HTML page with a form using method = "post" & a textbox with name = "stocklevel" - Receive the posted value the user places in the textbox - Where the stock level is below 20 print an "emergency reorder" statement - Where the stock level is between 20 & 49 print a "standard reorder" statement - Otherwise print "stock level is OK" COM427 19 Nested if statements • Using if … elseif… else to check textbox for numbers $input = $_POST["value"]; if ($input == "") { print "textbox value is blank – must enter a value"; } elseif (!is_numeric($input)) { print "enter a valid number in the textbox"; } else { …..[Input OK and can now be processed] } COM427 20 Program Loops • In order to perform repeated operations efficiently methods of looping through code instructions (for loops or while loops) are required • For loops are used when the number of iterations of the loops is known in advance • While loops continue until a condition is met (so the exact number of iterations is not known in advance) • Loops can be used for printing out rows of a table, printing sequences of values, simulating a number of values (e.g. dice throws, coin flips) COM427 21 For Loop General Format For (start expression, stop expression, increment expression) { [code statements] } FOR LOOP is used when you know the exact number of times a program loop needs to go round whereas a WHILE LOOP is used when you don’t (you need a condition to test when the loop needs to finish) COM427 22 For Loop example • <?php for ($i = 1; $i <= 5; $i = $i + 1) { print "Number $i <br />\n"; } ?> COM427 Output: 1 2 3 4 5 23 For Loop example explained for ($i = 1; $i < =5; $i = $i + 1) { print "Number $i <br />\n"; } Processing Output $i=1 1<=5 is true print "Number $i" $i = $i (1) + 1 so $i = 2 1 $i=2 2<=5 is true print "Number $i" $i = $i (2) + 1 so $i = 3 2 $i=3 3<=5 is true print "Number $i" $i = $i (3) + 1 so $i = 4 3 $i=4 4<=5 is true print "Number $i" $i = $i (4) + 1 so $i = 5 4 $i=5 5<=5 is true print "Number $i" $i = $i (5) + 1 so $i = 5 5 $i=6 6<=5 is not true END COM427 24 Exercise 3 – to try • A. Create a program to print out all the odd numbers from 1 to 21 using a for loop • B. Create a program to print out all the numbers from 10 to 1 using a for loop • C. Create a program to print the numbers from 1 to 5 with the square of each number (using a for loop) - (e.g. square of 1 is 1* 1 or 1, 2 is 2*2 or 4 etc) COM427 25 While Loop • While statement while (condition is true) { do code } • eg. <?php while(there are still rows to read from a database) { read in row; move to the next to row; } ?> COM427 26 While loop example • <?php $x = 1; // initial value of loop variable while ($x <=3) { // while end check condition print "number is $x<br>"; $x = $x + 1; // increment of loop variable } ?> Output: number is 1 number is 2 number is 3 COM427 27 While loop example explained $x = 1; while ($x < =3) { print "number is $x<br>"; $x = $x + 1; } Processing Output $x = 1 1<=3 is true print "number is $x" $x=$x (1) + 1 so $x=2 1 $x = 2 2<=3 is true print "number is $x" $x=$x (2) + 1 so $x=3 2 $x = 3 3<=3 is true print "number is $x" $x=$x (3) + 1 so $x=4 3 $x = 4 4<=3 is not true END COM427 28 Exercise 4 – to try • Repeat exercise 3 using while loops instead of for loops • A. Create a program to print out all the odd numbers from 1 to 21 • B. Create a program to print out all the numbers from 10 to 1 • C. Create a program to print the numbers from 1 to 5 with the square of each number COM427 29 Do while loop example • <?php $x = 1; do { $x = $x + 1; print "number is $x<br>"; } while ($x < =3); ?> Output: number is 2 number is 3 number is 4 COM427 30 Counting the number of loops • Counting - how many times a loop has gone round – Initialise a count variable before the loop – Increment the variable inside the loop – Print the final number after the loop has finished e.g. $count = 0; // initialise as 0 for ($i = 0; $i<10; $i=$i+1){ $count = $count + 1; // increment by 1 } print $count; // prints final count value - 10 COM427 31 Running Sum • Running sum counts values in a loop to give a total Initialise the sum variable before the loop – Increment the sum variable with a variable inside the loop (this value may be different at every loop iteration) – Print the final sum after the loop e.g. $sum = 0; // initialise as 0 for ($i = 1; $i<=10; $i=$i+1){ $sum= $sum + $i; // increment by value - $i } print $sum; // prints final count value – 55 // this sums 1+2+3+4+5+6+7+8+9+10 COM427 32 Exercise 5 – to try A. Use a for loop to print the odd numbers from 1 to 21 (rember Exercise 3A) and add these numbers together to give a total (running sum) B. Use a while loop to print numbers 1,2,3 etc adding the numbers together (running sum) while the total is less than 50 (while condition) and also count how many times the loop goes round (using loop count) printing sum & loop count COM427 33 Some Basic Maths Functions • • • • • Absolute value Square root, Round, Integer checker and Random number generation COM427 34 abs() Function • The absolute value function takes a single numerical argument and returns its absolute value (disregards negative sign). • For example, the following $x=abs(-5); $y=abs(42); print "x=$x y=$y"; • Will output – x=5 y=42 COM427 35 sqrt() Function • The square root function takes a single numerical argument and returns its square root. • For example, the following – $x=sqrt(25); – $y=sqrt(24); – print "x=$x y=$y"; • Will output – x=5 y=4.898979485566 COM427 36 round() Function • The round function takes a single numerical argument and returns the number rounded up or down to the nearest integer. • For example, the following – $x=round(-5.456); – $y=round(3.7342); – print "x=$x y=$y"; • Will output x=-5 y=4 COM427 37 round() Function • You can include 2nd argument to define the number of digits after the decimal point to round to. • For example, • $x=round(-5.456,2); • $y=round(3.7342,3); • print "x=$x y=$y"; • would output – x=-5.46 y=3.734 COM427 38 is_numeric() Function • is_numeric() is useful for determining whether a variable is a valid number or a numeric string. – It returns true or false. • Consider the following example... if (is_numeric($input)) { print "Got Valid Number=$input"; } else { print "Not Valid Number=$input"; } • If $input was "6" then would output: Got Valid Number=6 • If $input was "Happy" then would output: Not Valid Number=Happy COM427 39 rand() Function • Use rand( ) to generate a random number. – You can use random numbers to simulate a dice roll or a coin toss or to randomly select an advertisement banner to display. • rand( ) typically uses 2 arguments to define the range of numbers it should return (min and max limits), – For example the following returns a number 1 - 15 • $num = rand(1, 15); COM427 40 Coin flip using rand( ) • Rand( ) can be used to generate a random coin flip $flip = rand(0,1); if ($flip == 0){ print "Your random coin flip is heads"; } elseif ($flip == 1){ print "Your random coin flip is tails"; } • The random number generated is 0 or 1 – these can be assigned as heads or tails COM427 41 Exercise 6 – flip a coin Headsortails.html Given the web page shown on pages 35& 36 Create a php script gotflip.php Gotflip.php - Gets the user choice from radio button named "pick" with heads having value = 0 & tails having value =1 - use rand( ) to generate a random flip - check whether the user pick is correct or not - print the result - now change the program to display the user choice as heads or tails compared with the random flip result of heads or tails COM427 42 Headsortails.html <html><head><title> Coin Flip!</title></head><body> <font color="BLUE" size="4"> Please Pick Heads or Tails! </font> <form action="gotflip.php" method="post"><br> <input name="pick" value="0" type="radio">Heads<br> <input name="pick" value="1" type="radio">Tails<br><br> <input type="submit" value="Click To Submit" ><br><br> <input value="Erase and Restart" type="reset"> </form></body></html> COM427 43 Headortails Web Page COM427 44 Advanced Coin Flip – Exercise7A A. Create a PHP script to flip a coin 20 times and count how many flips are heads and how many are tails – Use a for loop (inside which the coin is flipped and count made) – Use the rand function to generate a coin flip – Use an if statement to check if the flip is heads or tails – Use a count (e.g. $numheads = $numheads +1;) to count the number of heads & tails as each loop goes round (must initialise this variable to 0 before the for loop) – Finally print out the total number of heads & the total number of tails COM427 45 Advanced Coin Flip - Exercise 7B • B. Now create a PHP script to flip a coin until either 20 heads or 20 tails have been flipped – – – – Use a while loop (what is the condition?) Count the number of heads and tails as before Count the total number of flips (different count variable) Finally print out the number of heads and tails and total number of flips COM427 46 Dice Roll using rand( ) • Rand( ) can be used to generate a random dice throw $roll = rand(1,6); print "Your random dice roll is $roll"; • The random number generated in this case can be a 1, 2, 3, 4, 5, or 6. COM427 47 Exercise 8A – dice roll • Change the coin toss program to a dice roll i.e. guessnumber.html & checkguess.php guessnumber.html - Displays a form with radio buttons to choose 1 – 6 checkguess.php - receives the user choice - generates a random dice roll - compares the choice with the random role - prints the result along with the choice and the random roll values COM427 48 Exercise 8B - Diceroll_twenty Write a php script to: - Assign a value to a guess - Roll one dice 20 times - Each time compare the guess with the random roll - Keep a count of how many times the guess is right - Print out the guess value along with the number of correct guesses COM427 49 Exercise 8C - RollsUntilWin Write a php script to: - Assign a value to a guess - Roll one dice until the correct answer is guessed - Print out COM427 50 Functions • As well as built-in predefined functions you can specify your own functions • This allows efficient code reuse if you need to use the functionality several times (reusability) • In larger programs functions are used to separate different areas of functionality and provide a good structure to the code COM427 51 Writing Your Own Functions • Use the following general format function function_name( ) { set of statements } COM427 52 Returning Values • Your functions can return data to the calling script. – For example, your functions can return the results of a computation. – You can use the PHP return statement to return a value to the calling script statement: return $result; COM427 53 Example function – get the larger of two numbers <?php function get_larger( $num1, $num2 ) { if ($num1 > $num2) { return($num1); } else { return($num2); } } $larger= get_larger(10, 20); print “larger number is $larger”; ?> COM427 54 Exercise 9 • Create a function to: – Input 3 numbers – Calculate the average of the numbers – Return the average • Use the function in a PHP script to – Use the function to average 4, 10 & 17 – Print the average value COM427 55 Using External Script Files • Sometime you will want to use scripts from external files. • PHP supports 2 related functions: – <?php require ("header.php"); include ("footer.php"); …. ?> The require() function produces a fatal error if it can’t insert the specified file. The include() function produces a warning if it can’t insert the specified file. • Both search for the file named within the double quotation marks and insert its PHP, HTML, or JavaScript code into the current file. COM427 56 Use of include( ) & require( ) • Include( ) & require( ) used to – – – – Create functions Headers Footers Elements to be used on multiple pages COM427 57 Simple include( ) example header.php <?php $colour = "green"; $items= "bottles"; ?> test.php <?php print "10 $colour $items"; // prints 10 include ("header.php"); print ?> "10 $colour $items"; COM427 // prints 10 green bottles 58