Professional Documents
Culture Documents
Unit-II
Controlling Program Flow: Writing Simple Conditional Statements - Writing More Complex
Conditional Statements – Repeating Action with Loops – Working with String and Numeric Functions.
Controlling Program Flow
The PHP programs we saw in the preceding chapter were straight forward: they accepted one
or more input values, performed calculations or comparisons with them, and returned a result.
In addition to storing and retrieving value in variables, PHP also lets programmers
evaluate different conditions during the course of a program and take decisions based on whether these
conditions evaluate to true or false. These conditions, and the actions associated with them, are expressed
by means of a programming construct called a conditional statement. PHP supports different types of
conditional statements, each one intended for a particular use.
i)The if statement
The simplest of PHP’s conditional statements is the if statement. This works much like the
English-language statement, “if X happens, do Y.” here’s a simple example, which contains a
conditional statement that checks if the value of the $number variable is less than 0 and prints a
notification message if so.
Example:
<?php
// if number is less than zero
//print message
$number = - 88;
If ($number < 0) {
echo ‘That number is negative’ ;}
?>
The key to the If statement is thus the condition to be evaluated, which is always enclosed in
parentheses.
ii) The if - else statement
The If statement is quite basic: it only lets you define what happens when the conditions specified
evaluates to true. But PHP also offers the if –else statement, an improved version of the if
construct that allows you to define an alternative set of action that the program should take when
the condition specified evaluates to false. In English, this statement would read, “if X happens, do
Y; otherwise, do Z.”
OPERATOR DESCRIPTION
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
=== Equal to and of the same type
Example:
<?php
//change message depending on whether
//number is less than zero or not
$number =-88;
If ($number<0)
{echo ‘that number is negative’;}
Else
{echo ‘that number is either positive or zero’;}
?>
Here, an if – else statements is used to account for two possible outcomes: a number less than
zero, and all other number.
The if -elseif-else statement lets you chain together multiple if –else statements, thus allowing the
programmer to define actions for more than just two possible outcomes. Consider the following
examples , which illustrates its use:
<?php
//handle multiple possibilities
//define a different message for each day $today=’Tuesday’;
If ($today == ‘Monday’)
{
Echo ‘Monday\’s child is fair of face. ’;}
Elseif ($today == ‘Tuesday’) {
echo ‘Tuesday\ ‘s child is full of grace. ‘;}
elseif ($today == ‘Wednesday’){
echo ‘Wednesday\ ‘s child is full of woe.’ ;}
elseif ($today == ‘Thursday’){
echo ‘Thursday\ ‘s child has far to go.’ ;}
elseif ($today == ‘Friday’){
echo ‘Thursday\ ‘s child is loving and giving.’ ;}
elseif ($today == ‘Saturday’){
echo ‘Thursday\ ‘s child works hard for a living.’ ;}
else{ echo ‘No information available for that day’;}
?>
Here, the program will output a different message for each day of the week (as set in the $today
variable).
ii) THE SWITCH-CASE STATEMENT
An alternative to the if-elseif-else statement is the switch-case statement, which does almost the
same thing: it tests a variable against a series of values until it finds a match, and then executes the
code corresponding to that match. Consider the following code listing, which is equivalent to the
preceding one:
<?php
// handle multiple possibilities
// define a different message for each day
$today = ‘Tuesday’ ;
Switch ($today)
{
Case ‘Monday’ :
echo ‘Monday\ ‘s child is fair of face. ‘ ;
break;
Case ‘Tuesday’ :
echo ‘Tuesday\ ‘s child is full of grace. ‘ ;
break;
Case ‘Wednesday’ :
echo ‘Wednesday\ ‘s child is full of woe. ‘ ;
break;
Case ‘Thursday’ :
echo ‘Thursday\ ‘s child is far to go. ‘ ;
break;
Case ‘Friday’ :
echo ‘Friday\ ‘s child is loving and giving. ‘ ;
break;
Case ‘Saturday’ :
echo ‘Saturday\ ‘s child is works hard for a living. ‘ ;
break;
default:
echo ‘No information available for that day’;
}
?>
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 we want, add a break statement to the end of each case block (as is done in the
previous listing) 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, is very useful as a “catch-all” handler for unforeseen situations.
<?php
// for employees with annual comp <= $15000
// those with a rating >= 3 get a $3000 bonus
If ($rating >= 3) {
If ($salary < 15000) {
$bonus = 5000 ;
}
}
else {
if ($salary < 15000)
{
$bonus = 3000 ;
}
}
?>
We can also combine conditional statements by using logical operators, such as the && or ||
operator. You learned about logical operators in the preceding chapter; Table 3-2 quickly recaps
the list.
Here’s an example of how these logical operators can be used with a conditional statement:
<?php
$year = 2008;
// leap years are divisible by 400
// or by 4 but not 100
If (($year % 400 == 0) || (($year % 100 !=0) && ($year % 4 == 0)))
{
echo “$year is a leap year.”;
}
?>
Like any good programming language, PHP also supports loops ---essentially, the ability
to repeat a series of actions until a pre-specified condition is fulfilled.
Loops are an important tool that help in automating repetitive tasks within a program. PHP
supports four different types of loops:
The while loop
The do-while loop
The for loop
The for each loop
Three of which are discussed in the following sections (the fourth type is explained in the
next chapter).
i) THE WHILE LOOP
The easiest type of loop to understand is the while loop, which repeats continuously while
a pre-specified condition is true. Here’s an example, which uses a loop to repeatedly print
an ‘X’ to the output page.
<?php
// repeat continuously until counter become 10
// output : ‘XXXXXXXXXXX’
$counter = 1;
While ($counter < 10)
{
echo ‘x’ ;
$counter++;
}
?>
ii) THE DO-WHILE LOOP
With a while loop, the condition to be evaluated is tested at the beginning of each loop
iteration. There’s also a variant of this loop, the do-while loop, the do-while loop, which
evaluates the condition at the end of each loop iteration.
<?php
// repeat continuously until counter become 10
// output : ‘XXXXXXXXXXX’
$counter = 1;
do
{
echo ‘x’ ;
$counter++;
}
While ($counter < 10);
?>
iii) THE FOR LOOP
The while and do-while loops are firely simple: they repeat for so long as the specified
condition remains true. But PHP also supports a more sophisticated type of loop, the for
loop, which is useful when you need to execute a set of statements a specific number of
times.
The best way to understand a for loop is by looking at some code. Here’s simple example,
Which lists the numbers between 1 and 10.
<?php
// repeat continuously until counter becomes 10
// output: ‘XXXXXXXXX’
For ($x=1; $x<10; $x++)
{
Echo “$x”;}
?>
The first of this is an assignment expression, which initialize the loop counter to a specific
values--- in this case, assigning the value 1 to the variable $x.
The second is a conditional expression, which must evaluate to either true or false; the loop
will continue to execute so long as this condition remains true. Once the condition becomes
false, the loop will stop executing.
The third is again an assignment expression, which is executed at the end of each loop
iteration, and which updates the loop counter with a new value – in this case, adding 1 to the
value of $x.
<?php
// generate ordered list of 6 times
echo “<01>”;
for ($x=1; $x<7; $x++)
{
echo “<li>Item $x</li>”;
}
echo “ </01>”;
?>
iv) 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 loop to dynamically generate
an HTML table.
Example:
<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:
Example:
<?php
$count = 0;
// loop 5 times
While ($count <= 4)
{
$count++;
// when the counter hits 3
// breakout of the loop
if ($count == 3)
{
Break;
}
echo “this is iteration #$count <br/>”;
}
?>
Example: Break and continue
<?php
$count = 0;
//loop 5 times
While ($count <= 4)
{
$count++;
// when the counter hits 3
// skip to the next iteration
if($count == 3)
{
Continue;
}
echo “this is iteration #$count <br/>”;
}
?>
PHP’s data types, including its operators for string and number manipulation.
But PHP lets us do a lot more than simply concatenate string and add values.
<?php
// extract substring
// output: ‘come’
$str = ‘welcome to nowhere’;
echo substr($str, 3, 4);
?>
d) Comparing, Counting, and Replacing Strings
If we 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);
?>
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: 5
$str = “the name’s Bond, James Bond”;
echo str_word_count($str);
?>
If we 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 ‘@’ with ‘at’
Output:
‘john at domain.net’
$str =’john@domain.net’;
Echo str_replace(‘@’ , ‘at’, $str);
?>
e) Formatting Strings
PHP’s trim() function can be used to remove leading or travelling whitespace from a string; this is
quite useful when processing data entered into a Web form. Here’s an example:
<?php
//remove leading and trailing whitespace
//output ‘a b c’
$str = ‘a b c ‘;
echo trim($str);
?>
Changing the case of a string is as simple as calling the strtolower() or strtoupper() function, as
illustrated in the next listing:
<?php
//change string case\
$str = ‘yabba dabba doo’;
//output: ‘yabba dabba doo’
Echo strtolower($str);
//output: ‘YABBA DABBA DOO’
echo strtoupper($str);
?>
We can also uppercase the first character of a string with the ucfirst() a function, or format String
in “word case” with the ucwords() function. The following listing demonstrates both these
functions:
<?php
//change string case
$str = ‘the yellow Brigands’;
//output: ‘The Yellow Brigands’
echo ucwords($str);
//output: ‘ The yellow brigands’
echo ucfirst($str);
?>
f) Working with HTML Strings
PHP also has some functions exclusively for working with HTML strings. First, the addslashes()
function, which automatically escapes special characters in a string with backslashes. Here’s an
example:
<?php0
// escape special characters
// output: ‘you\’re awake, aren\’t you?’
$str = “you’re awake , aren’t you?”;
echo addslashes($str);\
?>
We can reverse the work done by addslashes() with the aptly named striplashes() function, which
removes all the backslashes from a string. consider the following example, which illustrates:
<? php
//replace with HTML entities
//output: ‘<div width=">
// this is a div</div>’
$html = ‘<div width=”200”>This is a div</div>’;
echo htmlentities($html);
//replace line breaks with <br/>s
//output: ‘This is a bro<br />
$lines = ‘This is a bro Ken line’;
echo n12br($lines);
?>
We can reverse the effect of the htmlentities() and htmlspecialchars() functions with the
html_entitiy_decode() and htmlspecialchars_decode() functions.
Finally, the strip_tags() function searches for all HTML and PHP code within a string and
removes it to generate a “clean” string. Here’s an example:
<?php
// string HTML tags from string
//output: ‘please log in again’
$html =’<div width=”200”>please <strong>log in again</strong></div>’;
echo strip_tags($html);
?>
a. 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, and they’re illustrated in the next listing:
<?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. Here’s an example of both in action:
<?php
//calculate natural log of 100
//output: 2.30258509299
echo log(10);
//calculate exponent of 2.30258509299
//output: 9.99999999996
echo exp(2.30258509299);
?>
<?php
//generate a random number
echo rand();
//generate a random number between 10 and 99
echo rand (10,99);
?>
<?php
//convert to binary
//output: 1000
echo decbin(8);
//convert to hexodecimal
//output: 8
echo dechex(8);
//convert to octal
//output: 10
echo decoct(8);
//convert from octal
//output: 8
echo octdec(10);
//convert from hexodecimal
//output: 101
echo hexdec(65);
//convert from binary
//output: 8
echo bindec(1000);
?>
d. Formatting Numbers
When it comes to formatting numbers, PHP offers the number_format() function, which accept
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
$sum = 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() and sprintf() functions. These
functions, though very useful, can be intimidating to new users, and so that best way to
understand them is with an example.
SPECIFIER WHAT IT MEANS
%s String
%d Decimal number
%x Hexadecimal number
%o Octal number
%f Floating-point number
Table 3-5 Format Specifiers for the printf() and sprint() functions
Consider the nex listing, which shows them in action:
<?php
// format as decimal number
//output: 00065
printf(“%05d”,65);
//format as floating-point number
//output: 00239.000
printf(“%09.3f”,239);
//format as octal number
//output: 10
printf(“%40”, 8);
//format number
//incorporate into string
//output: ‘ I see 8 apples and 26.00 oranges’
prinf("I see %4d apples and %4.2f oranges”, 8,26);
?>