UNIT II Controlling Program Flow
UNIT II Controlling Program Flow
Syntax:
if(condition){
//code to be executed when condition is true
}
Example:
Let's check if a mark entered is greater than or equal to 80. If true an A grade is given.
PHP Code:
<?php
$mark = 120;
if($mark >= 80){
echo "you have an A";
}
?>
Output
you have an A
if...else statements: -
if-else statement, an improved version of the if construct that allows you to define an
alternative set of actions that the program should take when the condition specified evaluates
to false.
Use this statement if you want to execute a set of code when a condition is true and
another if the condition is not true.
Syntax:
if (condition){
//code to be executed when true }
else {
//code to be executed when false
}
Example:
Here, we are going to check if the letter entered is an F which will display female else
we display male.
PHP Code:
<?php
$gender = 'F';
if ($gender == 'F'){
echo "FEMALE";
}
else {
echo "MALE";
}
?>
Output
FEMALE
</form>
<?php
// if form submitted
// process form input
} else {
// retrieve number from POST submission
$num = $_POST['num'];
// test value for even-ness
// display appropriate message
if (($num % 2) == 0) {
echo 'You entered ' . $num . ', which is an even number.';
} else {
echo 'You entered ' . $num . ', which is an odd number.';
}
}
?>
</body>
</html>
Output
This program consists of two sections: the first half generates a Web form for the user
to enter a value, while the second half checks whether the value is odd or even and prints
an appropriate message. In most cases, these two sections would be in separate files;
they’ve been combined into a single PHP script by the magic of a conditional statement.
How does it work? Well, when the Web form is submitted, the $_POST variable will
contain an entry for the <input type='submit'...> element. A conditional test then
checks for the presence or absence of this variable: if absent, the program “knows” that
the Web form has not been submitted yet and so prints the form’s HTML code; if present,
the program “knows” that the Web form has been submitted and it then proceeds to test the
input value.
Testing the input value for evenness is handled by a second if-else conditional
statement. Here, the conditional expression consists of dividing the input value by 2
and testing if the remainder is zero. If this test returns true, one message is printed; else,
another message is printed.
Syntax:
if (condition1){
//code 1 to be executed
}
elseif(condition2) {
//code 2 to be executed
}
else{
//code to be executed if code 1 and code 2 are not true
}
Example:
We are going to grade students with the letters A, B, C, D, F based on their marks on 100.
PHP Code:
<?php
//defining a variable
$marks = 75;
if ($marks>79){
echo "A";
}
elseif($marks<=79&& $marks>60) {
echo "B";
}
elseif($marks<=60&& $marks>50) {
echo "C";
}
elseif($marks=50) {
echo "D";
}
else{
echo "F";
}
?>
Output: - B
switch statement: -
The switch statement is very similar to the if...else if…else statement. But in the cases
where your conditions are complicated like you need to check a condition with multiple
constant values, a switch statement is preferred to an if...else. The examples below will help
us better understand the switch statements.
Syntax:
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
default:
// code to be executed if n doesn't match any constant
}
Example:
Let's rewrite the example of if…..else statements using switch statements,
<?php
//variable definition
$gender = 'M';
switch ($gender) {
case 'F':
echo 'F is FEMALE';
break;
case 'M':
echo 'M is MALE';
break;
default:
echo 'Invalid choice';
}
?>
Output
M is MALE
The switch-case construct differs from the if-elseif-else construct in one important
way. Once PHP finds a case statement that evaluates to true, it executes not only the code
corresponding to that case statement, but also the code for all subsequent case statements. If
this is not what you want, add a break statement to the end of each case block to tell PHP to
break out of the switch-case statement block once it executes the code corresponding to the
first true case. Notice also the 'default' case: as the name suggests, this specifies the default
set of actions PHP should take if none of the other cases evaluate to true. This default case,
like the else branch of the if-elseif-else block.
Output
Like the previous project, this one too combines the Web form and its result page into
a single script, separated by an if-else conditional statement. Once the Scout enters his age
into the Web form and submits it, an if-elseif-else block takes care of defining four age
ranges (one for each tent), testing the input age against these ranges, and figuring out which
tent is most appropriate for the Scout. The age ranges are: 0–9 (Red tent); 10–11 (Blue tent);
12–14 (Green tent); and 14–17 (Black tent). Scouts over the age of 17 see a message asking
them to contact the Scoutmaster to arrange their accommodation.
Example
Here’s an example, which uses a loop to repeatedly print an 'x' to the output page.
<?php
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
Syntax
do {
code to be executed;
}while (condition);
Example
<?php
// repeat continuously until counter becomes 10
// output: 'xxxxxxxxx'
$counter = 1;
do {
echo 'x';
$counter++;
} while ($counter < 10);
?>
The conditional expression, which must evaluate to either true or false. assignment
expression, which is executed at the end of each loop iteration, and which updates the loop
counter with a new value
Example
which lists the numbers between 1 and 10:
<?php
// repeat continuously until counter becomes 10
// output: 1 2 3 4 5 6 7 8 9
for ($x=1; $x<10; $x++) {
echo "$x ";
}
?>
The loop begins by initializing the counter variable $x to 1; it then executes the
statements that make up the loop. Once it reaches the end of the first loop iteration, it updates
the loop counter by adding 1 to it, checks the conditional expression to ensure that the
counter hasn’t yet reached 10, and executes the loop once more. This process continues until
the counter reaches 10 and the conditional expression becomes false.
Combining Loops
Just as with conditional statements, it’s also possible to nest one loop inside another.
To illustrate, consider the next example, which nests one for loop inside another to
dynamically generate an HTML table.
<html>
<head>
<title></title>
</head>
<body>
<?php
// generate an HTML table
// 3 rows, 4 columns
echo "<table border=\"1\">";
for ($row=1; $row<4; $row++) {
echo "<tr>";
for ($col=1; $col<5; $col++) {
echo "<td>Row $row, Column $col</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
Output
This script utilizes two for loops. The outer loop is responsible for generating the
table rows, and it runs three times. On each iteration of this outer loop, an inner loop is also
triggered; this loop is responsible for generating the cells within each row, and it runs four
times. The end result is a table with three rows, each containing four cells.
// output: true
$str = '0';
echo (boolean) empty($str);
// output: true
unset($str);
echo (boolean)empty($str);
?>
Length string
The strlen() function returns the number of characters in a string. In below example
strlen() function is used to return length of "Hello world!"
Example
<?php
// calculate length of string
// output: 18
$str = 'Welcome to Belgaum';
echo strlen($str);
?>
Reverse string
Reversing a string is as simple as calling the strrev() function.
<?php
// reverse string
// output: 'edoc llams enO'
$str = 'One small code';
echo strrev($str);
?>
Repeat string
In case you need to repeat a string, PHP offers the str_repeat() function, which
accepts two arguments—the string to be repeated, and the number of times to repeat it.
Example:
<?php
// repeat string
// output: 'hihihi'
$str = 'hi';
echo str_repeat($str, 3);
?>
Comparing Strings
If you need to compare two strings, the strcmp() function performs a case-sensitive
comparison of two strings, returning a negative value if the first is “less” than the second,
a positive value if it’s the other way around, and zero if both strings are “equal.” Here are
some examples of how this works:
<?php
// compare strings
$a = "hello";
$b = "hello";
$c = "hEllo";
// output: 0
echo strcmp($a, $b);
// output: 1
echo strcmp($a, $c);
?>
Counting String
PHP’s str_word_count() function provides an easy way to count the number of
words in a string. The following listing illustrates its use:
<?php
// count words
// output: 4
$str = "The PHP string functions";
echo str_word_count($str);
?>
Replacing String
If you need to perform substitution within a string, PHP also has the str_replace()
function, designed specifically to perform find-and-replace operations. This function
accepts three arguments: the search term, the replacement term, and the string in which to
perform the replacement. Here’s an example:
<?php
// replace 'php' with 'world'
// output: Hello world
$str = 'Hello php';
echo str_replace("world", "php", $str);
?>
Doing Calculus
A common task when working with numbers involves rounding them up and down.
PHP offers the ceil() and floor() functions for this task.
<?php
// round number up
// output: 19
$num = 19.7;
echo floor($num);
// round number down
// output: 20
echo ceil($num);
?>
There’s also the abs() function, which returns the absolute value of a number. Here’s
an example:
<?php
// return absolute value of number
// output: 19.7
$num = -19.7;
echo abs($num);
?>
The pow() function returns the value of a number raised to the power of another:
<?php
// calculate 4 ^ 3
// output: 64
echo pow(4,3);
?>
The log() function calculates the natural or base-10 logarithm of a number, while the
exp() function calculates the exponent of a number. example of both
<?php
// calculate natural log of 100
// output: 2.30258509299
echo log(10);
// calculate log of 100, base 10
// output: 2
echo log(100,10);
// calculate exponent of 2.30258509299
// output: 9.99999999996
echo exp(2.30258509299);
?>
// output: 10
echo decoct(8);
// convert from octal
// output: 8
echo octdec(10);
// convert from hexadecimal
// output: 101
echo hexdec(65);
// convert from binary
// output: 8
echo bindec(1000);
?>
Formatting Numbers
When it comes to formatting numbers, PHP offers the number_format() function,
which accepts four arguments: the number to be formatted, the number of decimal places to
display, the character to use instead of a decimal point, and the character to use to separate
grouped thousands (usually a comma). Consider the following example, which illustrates:
<?php
// format number (with defaults)
// output: 1,106,483
$num = 1106482.5843;
echo number_format($num);
// format number (with custom separators)
// output: 1?106?482*584
echo number_format($num,3,'*','?');
?>
For more control over number formatting, PHP offers the printf() functions. These
functions, though very useful, can be intimidating to new users, and so the best way to
understand them is with an example. Consider the next listing, which shows them in action:
<?php
// format as decimal number
// output: 00065
printf("%05d", 65);
// format as floating-point number
// output: 239.0000
printf("%0.4f", 239);
// format as octal number
// output: 10
printf("%4o", 8);
// format number
// incorporate into string
// output: 'I see part a 10 programs and part b 5.00 programs.
printf("I see part a %d programs and part b %0.2f programs", 10, 5);?>