Web Programming
PHP flow-control &
functions
COM427 1
Output Statement
print
• Only one parameter
• Return a value: 1 if it succeeded; 0 if it failed
echo
• With parentheses, only one single string parameter is
acceptable
• Without parentheses, any number of parameters can
appear
• Does not return a value
printf
• Control over the format of displayed data
COM427 2
echo command examples
My name is $name”;
?>
Output : Joe
My name is Joe
COM427 3
Printf( format, argument)
Formats: %c single character; %s string; %f floating point number
%u unsigned decimal number
Output: Joe is 25 years old
COM427 4
Conditional Test Statement
the if statement,
the elseif clause,
the else clause,
the switch statement.
COM427 5
If statement
General Format
If (condition) statement;
If (condition) {
statement;
…………..
}
COM427 6
If …. ElseIf
General Format
if (condition) {
statement;
}
elseIf (condition) {
statement;
}
else statement;
COM427 7
Comparison Operators
Test Effect Example Result
Operator
== Equal to if ($x == 6){ Run the second and third
$x = $y + 1; statements if the value of $x is
$y = $x + 1; equal to 6.
}
!= Not equal to if ($x != $y) { Run the second statement if the
$x = 5 + 1; value of $x is not equal to the
} value of $y.
Greater than if ($x > 51) { Run the second statement if the
print "OK"; value of $x is greater than 51.
}
>= Greater than or if (16 >= $x) { Run the second statement if 16
equal to print "x=$x"; is greater than or equal to the
} value of $x.
COM427 9
Using multiple conditions
When using more than one condition the logical AND & OR is
required
In PHP AND is && and OR is II (and negation is !)
If x is greater than 10 but less than 20 is expressed as
If ($x > 10 && $x 100) {
………………..
COM427 10
Switch Statement (multiple if…..
elseif..)
General Format
switch (expression) {
Case “value 1":
statement;
break;
Case “value 2“:
statement;
break;
Default:
statement;
}
COM427 11
Switch example
COM427 12
Ternary Conditional Operator
Ternary conditional operator (?:) can be used:
$variable = condition ? if true : if false ;
$grade >= 80 ? $rank=„A‟ : $rank = „B‟;
COM427 13
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_form.html age_receiver.php
COM427 14
Age_receive.php (part)
\n";
$Age = $_POST["myAge"];
if ($Age \n");
} elseif (if ($Age >= 18 && $Age \n";
elseif ($Age >= 50) {
print "You can retire soon – hurrah! \n";
} else {
print “number not a positive number";
}
?>
COM427 15
Exercise – to try
Create a php program to check the stock level
if (condition) {
statement; - Assume that an HTML page with a form using
} method = “post” & a textbox with
name = “stocklevel”
elseIf (condition) {
statement; - Get the value the user places in the textbox
}
- Where the stock level is below 20 print an
else statement;
emergency reorder command,
- Where the stock level is between 20 & 49
print a standard reorder command
- Otherwise print stock level is OK
COM427 16
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 17
For Loop example
\n"; 3
4
}
5
?>
COM427 18
For Loop example explained
for ($i = 1; $i \n";
}
Processing Output
$1=1 1
COM427 20
While loop example
”;
$x = $x + 1;
}
?>
Output: number is 1
number is 2
number is 3
COM427 21
While loop example explained
$x = 1;
while ($x ”;
$x = $x + 1;
}
Processing Output
$x = 1 1”;
}
while ($x
Output: number is 2
number is 3
number is 4
COM427 23
Some Basic Math Functions
Absolute value
Square root,
Round,
Integer checker and
Random number generation
COM427 24
Example – pick up number
• form file: guesstwodigits.html
• receiving file: guesstwo_receive.php
COM427 25
The abs() Function
The absolute value function takes a
single numerical argument and returns its
absolute value.
For example, the following
$x=abs(-5);
$y=abs(42);
print "x=$x y=$y";
Will output
• x=5 y=42
COM427 26
The 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 27
The 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 28
The 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 29
The 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 : Got Valid Number=6
If $input was “Happy” then would output:
Not Valid Number=Happy
COM427 30
The 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 31
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 32
Example to try
1. 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
• Use a count ($var = $var +1;) to count the number of heads & tails
as each loop goes round
• Finally print out the total number of heads & the total number of tails
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
• Count the number of flips
• Finally print out the number of heads and tails and total number of
flips
COM427 33
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 34
Example to try – toss a coin
Headsortails.html
Given the web page shown on pages 32 & 33
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 35
Headsortails.html
Coin Flip!
Please Pick Heads or Tails!
Heads
Tails
COM427 36
Headortails Web Page
COM427 37
Example to try – 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 38
Diceroll_twenty.php
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 39
RollsUntilWin.php
Write a php script to:
- Assign a value to a guess
- Roll one dice until the correct answer is guessed
- Print out
COM427 40
Writing Your Own Functions
Use the following general format
function function_name( ) {
set of statements
}
COM427 41
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 42
Example function – get the larger
of two numbers
$num2) {
return($num1);
} else {
return($num2);
}
}
$larger= get_larger(10, 20);
print “larger number is $larger”;
?>
COM427 43
Exercise to try
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 44
Using External Script Files
Sometime you will want to use scripts from external files.
PHP supports 2 related functions:
• 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 45
Use of include( ) & require( )
Include( ) & require( ) used to
• Create functions
• Headers
• Footers
• Elements to be used on multiple pages
COM427 46
Simple include( ) example
header.php
test.php
COM427 47