web programming php flow of control & functions com4271

58
Web Programming PHP flow of control & functions COM427 1

Upload: maximillian-banks

Post on 12-Jan-2016

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Web Programming PHP flow of control & functions COM4271

Web Programming

PHP flow of control & functions

COM427 1

Page 2: Web Programming PHP flow of control & functions COM4271

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

Page 3: Web Programming PHP flow of control & functions COM4271

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

Page 4: Web Programming PHP flow of control & functions COM4271

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

Page 5: Web Programming PHP flow of control & functions COM4271

If statementIf a condition is true then some consequence follows

General Format

If (condition) statement;

If (condition) {statement; // consequence of a true condition…………..}

COM427 5

Page 6: Web Programming PHP flow of control & functions COM4271

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

Page 7: Web Programming PHP flow of control & functions COM4271

If …. ElseIf

General Format

if (condition) {statement;}elseif (condition) {statement;}else statement;

COM427 7

Page 8: Web Programming PHP flow of control & functions COM4271

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

Page 9: Web Programming PHP flow of control & functions COM4271

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 equalto

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

Page 10: Web Programming PHP flow of control & functions COM4271

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.

>= Greater than orequal 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"; print "x=$x";}

Run the second and third statements if the value of $x is less than or equal to the value of $y.

COM427 10

Page 11: Web Programming PHP flow of control & functions COM4271

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

Page 12: Web Programming PHP flow of control & functions COM4271

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

Page 13: Web Programming PHP flow of control & functions COM4271

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

Page 14: Web Programming PHP flow of control & functions COM4271

Switch Statement (multiple if….. elseif..)

General Format

switch (expression) { Case "value 1": statement; break; Case "value 2": statement; break; Default: statement;}

COM427 14

Page 15: Web Programming PHP flow of control & functions COM4271

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

Page 16: Web Programming PHP flow of control & functions COM4271

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

Page 17: Web Programming PHP flow of control & functions COM4271

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

Page 18: Web Programming PHP flow of control & functions COM4271

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

Page 19: Web Programming PHP flow of control & functions COM4271

Exercise 2 – to tryif (condition) {statement;}elseif (condition) {statement;}else statement;

COM427 19

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"

Page 20: Web Programming PHP flow of control & functions COM4271

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

Page 21: Web Programming PHP flow of control & functions COM4271

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

Page 22: Web Programming PHP flow of control & functions COM4271

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

Page 23: Web Programming PHP flow of control & functions COM4271

For Loop example

• <?php for ($i = 1; $i <= 5; $i = $i + 1) {

print "Number $i <br />\n"; } ?>

COM427 23

Output: 1

2345

Page 24: Web Programming PHP flow of control & functions COM4271

For Loop example explained

for ($i = 1; $i < =5; $i = $i + 1) { print "Number $i <br />\n";

}

COM427 24

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

Page 25: Web Programming PHP flow of control & functions COM4271

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

Page 26: Web Programming PHP flow of control & functions COM4271

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

Page 27: Web Programming PHP flow of control & functions COM4271

While loop example• <?php

$x = 1; // initial value of loop variablewhile ($x <=3) { // while end check conditionprint "number is $x<br>";$x = $x + 1; // increment of loop variable}

?>

Output: number is 1 number is 2

number is 3

COM427 27

Page 28: Web Programming PHP flow of control & functions COM4271

While loop example explained$x = 1; while ($x < =3) { print "number is $x<br>";$x = $x + 1;}

COM427 28

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

Page 29: Web Programming PHP flow of control & functions COM4271

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

Page 30: Web Programming PHP flow of control & functions COM4271

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

Page 31: Web Programming PHP flow of control & functions COM4271

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

Page 32: Web Programming PHP flow of control & functions COM4271

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

Page 33: Web Programming PHP flow of control & functions COM4271

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

Page 34: Web Programming PHP flow of control & functions COM4271

Some Basic Maths Functions

• Absolute value• Square root, • Round, • Integer checker and• Random number generation

COM427 34

Page 35: Web Programming PHP flow of control & functions COM4271

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

Page 36: Web Programming PHP flow of control & functions COM4271

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

Page 37: Web Programming PHP flow of control & functions COM4271

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

Page 38: Web Programming PHP flow of control & functions COM4271

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

Page 39: Web Programming PHP flow of control & functions COM4271

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

Page 40: Web Programming PHP flow of control & functions COM4271

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

Page 41: Web Programming PHP flow of control & functions COM4271

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

Page 42: Web Programming PHP flow of control & functions COM4271

Exercise 6 – flip a coinHeadsortails.html Given the web page shown on pages 35& 36 Create a php script gotflip.phpGotflip.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 tailsCOM427 42

Page 43: Web Programming PHP flow of control & functions COM4271

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

Page 44: Web Programming PHP flow of control & functions COM4271

Headortails Web Page

COM427 44

Page 45: Web Programming PHP flow of control & functions COM4271

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

Page 46: Web Programming PHP flow of control & functions COM4271

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

Page 47: Web Programming PHP flow of control & functions COM4271

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

Page 48: Web Programming PHP flow of control & functions COM4271

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

COM42748

Page 49: Web Programming PHP flow of control & functions COM4271

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

Page 50: Web Programming PHP flow of control & functions COM4271

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

Page 51: Web Programming PHP flow of control & functions COM4271

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

Page 52: Web Programming PHP flow of control & functions COM4271

Writing Your Own Functions• Use the following general format

function function_name( ) {

set of statements

}

COM427 52

Page 53: Web Programming PHP flow of control & functions COM4271

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

Page 54: Web Programming PHP flow of control & functions COM4271

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”;

?>

COM42754

Page 55: Web Programming PHP flow of control & functions COM4271

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

Page 56: Web Programming PHP flow of control & functions COM4271

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.

COM427 56

The require() function produces a fatalerror if it can’t insert the specified file.

The include() function produces a warningif it can’t insert the specified file.

Page 57: Web Programming PHP flow of control & functions COM4271

Use of include( ) & require( )

• Include( ) & require( ) used to– Create functions– Headers– Footers– Elements to be used on multiple pages

COM427 57

Page 58: Web Programming PHP flow of control & functions COM4271

Simple include( ) example

header.php <?php$colour = "green";$items= "bottles";?>

test.php<?phpprint "10 $colour $items"; // prints 10

include ("header.php");

print "10 $colour $items"; // prints 10 green bottles?>

COM427 58