0% found this document useful (0 votes)
2 views

UNIT II Controlling Program Flow

This document covers controlling program flow in PHP, focusing on conditional statements and loops. It explains the use of if, else, elseif, switch statements, and various loop types such as while, do...while, for, and foreach, providing syntax and examples for each. Additionally, it discusses nesting conditional statements and loops to create more complex logic in programs.

Uploaded by

mparvezkhazi3463
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT II Controlling Program Flow

This document covers controlling program flow in PHP, focusing on conditional statements and loops. It explains the use of if, else, elseif, switch statements, and various loop types such as while, do...while, for, and foreach, providing syntax and examples for each. Additionally, it discusses nesting conditional statements and loops to create more complex logic in programs.

Uploaded by

mparvezkhazi3463
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT-II CONTROLLING PROGRAM FLOW

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:


PHP supports a number of traditional programming constructs for controlling the flow
of execution of a program. Conditional statements, such as if/else and switch, allow a
program to execute different pieces of code, or none at all, depending on some condition.
Loops, such as while and for, support the repeated execution of particular code.

Writing Simple Conditional Statements


if statement: -
The simplest of PHP’s conditional statements is the if statement. With the if
statement your code only executes only when the condition is true.
If the condition evaluates to true, the code within the curly braces is executed; if it
evaluates to false, the code within the curly braces is skipped. This true/ false test is
performed using PHP’s comparison operators

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.

NITIN BELGAONKAR - JGI 1


UNIT-II CONTROLLING PROGRAM FLOW

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

Testing Odd and Even Numbers


Now that you know the basics of conditional statements, let’s look at an example of
how they can be used. The following program will ask the user to enter a number into a Web
form, test it to see whether it is odd or even, and return a corresponding message. Here’s the
code (oddeven.php):
<html>
<head>
<title>Odd/Even Number Tester</title>
</head>
<body>
<h2>Odd/Even Number Tester</h2>
<?php
// if form not yet submitted
// display form
if (!isset($_POST['submit'])) {
?>
<form method="post" action="oddeven.php">
Enter value: <br />
<input type="text" name="num" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />

NITIN BELGAONKAR - JGI 2


UNIT-II CONTROLLING PROGRAM FLOW

</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.

NITIN BELGAONKAR - JGI 3


UNIT-II CONTROLLING PROGRAM FLOW

Writing More Complex Conditional Statements


if...elseif...else statements: -
The if...elseif...else statement executes different codes for more than two conditions.
In a situation where you have several conditions, for example a program to grade students
based on their marks with the letters A, B, C, D, F. the if...elseif...else is used for this.
There’s one important thing to remember about the if-elseif-else construct: as soon as
one of the conditional statements evaluates to true, PHP will execute the corresponding code,
skip the remaining conditional tests, and jump straight to the lines following the entire if-
elseif-else block. So, even if more than one of the conditional tests evaluates to true, PHP will
only execute the code corresponding to the first true test

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

NITIN BELGAONKAR - JGI 4


UNIT-II CONTROLLING PROGRAM FLOW

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.

NITIN BELGAONKAR - JGI 5


UNIT-II CONTROLLING PROGRAM FLOW

Combining Conditional Statements


PHP allows one conditional statement to be nested within another, to allow for more
complex decision-making.
nested if...else statements: -
When you find if...else statements inside an if...else statement the statements
are nested. With this statement, you can get alternatives results when a condition
is true or false.
Syntax:
if (condition 1 )
{
if (condition 2 )
{
// code1 to be executed
}
else
{
// code 2 to be executed
}
}
else
{
// code 4 to be executed
}
Example:
Let's compare tow numbers using the nested if statement.
PHP code:
<?php
$number1 = 40;
$number2 = 12;
if ($number1 != $number2) {
echo 'number1 is different from number2';
echo '<br>';
if ($number1 > $number2) {
echo 'number1 is greater than number2';
} else {
echo 'number2 is greater than number1';
}
} else {
echo 'number1 is equal to number2';
}
?>
Output
number1 is different from number2
number1 is greater than number2

NITIN BELGAONKAR - JGI 6


UNIT-II CONTROLLING PROGRAM FLOW

Assigning Boy Scouts to Tents


Let’s now use the if-elseif-else statement to create a small application for Scout
masters everywhere: a Web tool that can automatically assign Scouts to the correct tent
during camping expeditions, on the basis of their age. This application presents Scouts with a
Web form into which they can enter their age; it then assigns them to one of four tents—Red,
Green, Blue, and Black—with other Scouts of approximately the same age. Here’s the code
(tent.php):
<html>
<head><title>Tent Assignment</title></head>
<body>
<h2>Tent Assignment</h2>
<?php
// if form not yet submitted
// display form
if (!isset($_POST['submit'])) {
?>
<form method="post" action="tent.php">
Enter your age: <br />
<input type="text" name="age" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
// if form submitted
// process form input
} else {
// retrieve age from POST submission
$age = $_POST['age'];
// assign to one of four tents
// based on which age "bin" it falls into
if ($age <= 9) {
echo "You're in the Red tent.";
} elseif ($age > 9 && $age <= 11) {
echo "You're in the Blue tent.";
} elseif ($age > 11 && $age <= 14) {
echo "You're in the Green tent.";
} elseif ($age > 14 && $age <= 17) {
echo "You're in the Black tent.";
} else {
echo "You'd better get in touch with the Scoutmaster.";
}
}
?>
</body>
</html>

NITIN BELGAONKAR - JGI 7


UNIT-II CONTROLLING PROGRAM FLOW

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.

Repeating Action with Loops


Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports following four loop types.
• while − loops through a block of code if and as long as a specified condition is true.
• do...while − loops through a block of code once, and then repeats the loop as long as a
special condition is true.
• for − loops through a block of code a specified number of times.
• foreach − loops through a block of code for each element in an array.

while loop statement: -


The while statement will execute a block of code if and as long as a test expression is
true. If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until the test
expression is found to be false.
Syntax
while (condition)
{ code to be executed; }

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;

NITIN BELGAONKAR - JGI 8


UNIT-II CONTROLLING PROGRAM FLOW

while ($counter < 10) {


echo 'x';
$counter++;
}
?>

do...while loop statement : -


The do...while statement will execute a block of code at least once. It then will repeat
the loop as long as a condition is true. with a do-while loop, the condition to be evaluated
now appears at the bottom of the loop block, rather than the beginning.

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);
?>

Difference between a while loop and a do-while loop


• with a while loop, if the conditional expression evaluates to false on the first pass
itself, the loop will never be executed.
• With a do-while loop, on the other hand, the loop will always be executed once, even
if the conditional expression is false, because the condition is evaluated at the end of
the loop iteration rather than the beginning.

for loop statement: -


The for statement is used when you know how many times you want to execute a
statement or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed; }
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

NITIN BELGAONKAR - JGI 9


UNIT-II CONTROLLING PROGRAM FLOW

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

NITIN BELGAONKAR - JGI 10


UNIT-II CONTROLLING PROGRAM FLOW

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.

Working with String and Numeric Functions


Using String Functions: -
PHP has over 75 built-in string manipulation functions, supporting operations ranging
from string repetition and reversal to comparison and search-and-replace.

Checking for Empty Strings: -


The empty() function returns true if a string variable is “empty.” Empty string
variables
are those with the values '', 0, '0', or NULL. The empty() function also returns true
when used with a non-existent variable. Here are some examples:
<?php
// test if string is empty
// output: true
$str = ' ';
echo (boolean) empty($str);
// output: true
$str = null;
echo (boolean) empty($str);

NITIN BELGAONKAR - JGI 11


UNIT-II CONTROLLING PROGRAM FLOW

// 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

NITIN BELGAONKAR - JGI 12


UNIT-II CONTROLLING PROGRAM FLOW

// 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);
?>

Formatting Strings function


trim()
PHP’s trim() function can be used to remove leading or trailing 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);
?>

NITIN BELGAONKAR - JGI 13


UNIT-II CONTROLLING PROGRAM FLOW

Lower and Upper case string


strtolower() function is used to convert uppercase letter into lowercase letter.
strtoupper() function is used to convert lowercase letter into uppercase letter.
<?php
// change string case
$str = 'HELLO WORLD';
// output: hello world
echo strtolower($str);
$str1 = ' hello world ';
// output: HELLO WORLD
echo strtoupper($str1);
?>

ucfirst() and ucwords()


You can also uppercase the first character of a string with the ucfirst() function,
or format a string in “word case” with the ucwords() function.
<?php
// change string case
$str = 'hello world';
// output: Hello World
echo ucwords($str);
// output: Hello world
echo ucfirst($str);
?>

NITIN BELGAONKAR - JGI 14


UNIT-II CONTROLLING PROGRAM FLOW

Using Numeric Functions: -


PHP has over 50 built-in functions for working with numbers, ranging from simple
formatting functions to functions for arithmetic, logarithmic, and trigonometric
manipulations.

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

NITIN BELGAONKAR - JGI 15


UNIT-II CONTROLLING PROGRAM FLOW

// 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);
?>

Generating Random Numbers


Generating random numbers with PHP is pretty simple too: the language’s built-in
rand() function automatically generates a random integer greater than 0. You can
constrain it to a specific number range by providing optional limits as arguments. The
following is the example:
<?php
// generate a random number
// output: 1359272112
echo rand();
// generate a random number between 10 and 99
// output: 51
echo rand(10,99);
?>

Converting Between Number Bases


PHP comes with built-in functions for converting between binary, decimal, octal, and
hexadecimal bases. Here’s an example which demonstrates the bindec(), decbin(), decoct(),
dechex(), hexdec(), and octdec() functions in action:
<?php
// convert to binary
// output: 1000
echo decbin(8);
// convert to hexadecimal
// output: 8
echo dechex(8);
// convert to octal

NITIN BELGAONKAR - JGI 16


UNIT-II CONTROLLING PROGRAM FLOW

// 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);?>

NITIN BELGAONKAR - JGI 17

You might also like