PHP flow of control & functions

Slides:



Advertisements
Similar presentations
Microsoft® Small Basic
Advertisements

1 JavaScript: Control Structures II. 2 whileCounter.html 1 2
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Computer Science 1620 Loops.
1 Controlling Script Flow! David Lash Chapter 3 Conditional Statements.
XP New Perspectives on Microsoft Office Excel 2003, Second Edition- Tutorial 2 1 Microsoft Office Excel 2003 Tutorial 2 – Working With Formulas and Functions.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
1 Computing for Todays Lecture 8 Yumei Huo Spring 2006.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
XP Abdul Hameed 1 Microsoft Office Excel 2013 Tutorial 2 – Working With Formulas and Functions.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
1 Session 3: Flow Control & Functions iNET Academy Open Source Web Programming.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Flow of Control Part 1: Selection
Slide 3-1 CHAPTER 3 Conditional Statements Objectives To learn to use conditional test statements to compare numerical and string data values To learn.
30/10/ Iteration Loops Do While (condition is true) … Loop.
1 Module 3 Conditional Statements. Objectives  Conditional test statements to compare numerical and string data values  Looping statements to repeat.
9-1 COBOL for the 21 st Century Nancy Stern Hofstra University Robert A. Stern Nassau Community College James P. Ley University of Wisconsin-Stout (Emeritus)
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Introduction to the Essentials of Excel COMP 066.
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
XP 1 Microsoft Office Excel 2003 Working With Formulas and Functions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Chapter 7 Problem Solving with Loops
XP 1 ﴀ New Perspectives on Microsoft Office 2003, Premium Edition Excel Tutorial 2 Microsoft Office Excel 2003 Tutorial 2 – Working With Formulas and Functions.
Decision Making and Branching (cont.)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Copyright © 2003 Pearson Education, Inc. Slide 4-1 The Web Wizard’s Guide to PHP by David Lash.
Copyright © 2003 Pearson Education, Inc. Slide 3-1 The Web Wizard’s Guide to PHP by David A. Lash.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Loops BIS1523 – Lecture 10.
Python: Control Structures
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
Chapter 6: Conditional Statements and Loops
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
CS1100 Computational Engineering
The Web Wizard’s Guide to PHP
Chapter (3) - Looping Questions.
Iteration: Beyond the Basic PERFORM
Do While (condition is true) … Loop
Coding Concepts (Basics)
The Web Wizard’s Guide to PHP by David Lash
SELECTIONS STATEMENTS
Chapter 5: Control Structures II (Repetition)
Conditionals and Loops
REPETITION Why Repetition?
Presentation transcript:

PHP flow of control & functions Web Programming PHP flow of control & functions COM427

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

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

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

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

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

If …. ElseIf General Format if (condition) { statement; } elseif (condition) { else statement; COM427

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

Comparison Operators Test Operator Effect Example Result == Equal to 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; value of $x is less than 100. COM427

Comparison Operators (2) Test Operator Effect Example Result > Greater than if ($x > 51) { print "OK"; } Run the second statement if the value of $x is greater than 51. >= than or equal to if (16 >= $x) { print "x=$x"; Run the second statement if 16 is greater than or equal to the value of $x. <= Less than or equal to if ($x <= $y) { print "y=$y"; Run the second and third statements if the value of $x is less than or equal to the value of $y. COM427

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

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 COM427

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

Switch Statement (multiple if….. elseif..) General Format switch (expression) { Case "value 1": statement; break; Case "value 2": Default: } COM427

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"; Default: Print "Stay at home"; } ?> COM427

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

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

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

Exercise 2 – to try if (condition) { statement; } elseif (condition) { 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

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

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

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

For Loop example <?php for ($i = 1; $i <= 5; $i = $i + 1) { print "Number $i <br />\n"; } ?> Output: 1 2 3 4 5 COM427

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

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

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

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

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

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

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

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

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

Exercise 5 – to try 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) 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

Some Basic Maths Functions Absolute value Square root, Round, Integer checker and Random number generation COM427

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

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

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

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

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

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

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

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

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

Headortails Web Page COM427

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

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

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

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

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

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

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

Writing Your Own Functions Use the following general format function function_name( ) { set of statements } COM427

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

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

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

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"); …. ?> Both search for the file named within the double quotation marks and insert its PHP, HTML, or JavaScript code into the current file. 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. COM427

Use of include( ) & require( ) Include( ) & require( ) used to Create functions Headers Footers Elements to be used on multiple pages COM427

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"; // prints 10 green bottles ?> COM427