UNIT 2 PHP and MYSQL (Controlling Program Flow)
UNIT 2 PHP and MYSQL (Controlling Program Flow)
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
UNIT 2
Controlling Program Flow: Writing Simple Conditional Statements -Writing More Complex
Conditional Statements - Repeating Action with Loops-Working with String Functions.
It can perform different actions based on the results of a logical or comparative test. You’ll also learn
how to automate repetitive actions using loops, and find out more about PHP’s built-in functions for
working with strings and numbers.
PHP allows us to perform actions based on some type of conditions that may be logical or
comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action would be
performed as asked by the user.
1.if Statement
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax :
if (condition)
{
//code to be executed
}
}
Page | 1
Flowchart
Example : Example:
<?php <?php
$num=12; $x = 12;
if ($x > 0)
if($num<100)
{ {
echo "$num is less than 100"; echo "The number is positive";
} }
?> ?>
Flow Chart:
Example Example:
<?php <?php
$num=12; $x = -12;
if($num%2==0) if ($x > 0)
{ echo "The number is positive";
echo "$num is even number";
} else
else
{ echo "The number is negative";
echo "$num is odd number"; ?>
}
?>
Output: The number is negative
Output: 12 is even number
Page | 3
<body>
<h2>Odd/Even Number Tester</h2><?php
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" />
</form>
<?php
}
else
{
$num = $_POST['num'];
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
:
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
1.if-elseif-else Statement
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.
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 (condition) Flowchart
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
elseif
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
Page | 5
Example
<?php
$marks=69;
if ($marks<33)
{
echo "fail";
}
else if ($marks>=34 && $marks<50)
{
echo "D grade";
}
else if ($marks>=50 && $marks<65)
{
echo "C grade";
}
else if ($marks>=65 && $marks<80)
{
echo "B grade";
}
else if ($marks>=80 && $marks<90)
{
echo "A grade";
}
else if ($marks>=90 && $marks<100)
{
echo "A+ grade";
}
else
{
echo "Invalid input";
}
?>
Output:
B grade
Example:
<?php
$x = "August";
if ($x == "January")
{
echo "Happy Republic Day";
}
elseif ($x == "August")
{
echo "Happy Independence Day!!!";
}
else
{
echo "Nothing to show";
}
?>
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
2.switch-case Statement
The “switch” performs in various cases i.e., it has various cases to which it matches the condition and
appropriately executes a particular case block. It first evaluates an expression and then compares with
the values of each case.
If a case matches then the same case is executed. To use switch, we need to get familiar with two
different keywords namely, break and default.
The break statement is used to stop the automatic control flow into the next cases and exit from the
switch case.
The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Flowchart:
Page | 7
Example
<?php
$num=20;
switch($num)
{
case 10: echo("number is equals to 10");
break;
case 20: echo("number is equal to 20");
break;
case 30: echo("number is equal to 30");
break;
default: echo("number is not equal to 10, 20 or 30");
}
?>
Output: number is equal to 20
<?php
$ch = "BCA";
switch ($ch)
{
case "BCA":echo "BCA is 3 years course";
break;
case "Bsc": echo "Bsc is 3 years course";
break;
case "B.Tech": echo "B.Tech is 4 years course";
break;
case "B.Arch": echo "B.Arch is 5 years course";
break;
default: echo "Wrong Choice";
break;
}
?>
Flowchart
Example
<? php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18)
{
echo “Eligible to give vote”;
}
else
{
echo “Not Eligible to give vote”;
}
}
?>
Page | 9
Repeating Actions with Loops
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 helps in automating repetitive
tasks within a program.
PHP supports five different types of loops
1. The while Loop
2. The do-while Loop
3. The for Loop
4. Combining Loops(Nested for loops)
5. The foreach Loop
Syntax: Flowchart
while (if the condition is true)
{
// code is executed
}
Example:
<?php
$counter = 1;
while ($counter < 10) {
echo 'x';
$counter++;
}
?>
Output: 'xxxxxxxxx'
Example:
<?php
$num = 1;
while ($num <=10)
{
echo $num, "\n";
$num ++;
}
?>
Output: 1 2 3 4 5 6 7 8 9 10
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
Syntax: Flowchart
do
{
//code is executed
} while (if condition is true);
Example:
<?php
$num = 1;
do
{
echo $num, "\n";
$num ++;
} while ($num <=10);
?>
Output: 1 2 3 4 5 6 7 8 9 10
Example:
<?php
$counter = 1;
do {
echo 'x';
$counter++;
} while ($counter < 10);
?>
Output: 'xxxxxxxxx'
NOTE
The difference in behavior between a while loop and a do-while loop has one important implication: 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.
Page | 11
Syntax
for (initialization expression; test condition; update expression)
{
code to be executed for each iteration;
}
Parameters:
• initialization expression: Initialize the loop counter value
• test condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• update expression: Increment and decrement the loop counter value
Flowchart:
Output: 1 2 3 4 5 6 7 8 9
{
code to be executed for each iteration;
}
}
Parameters:
• initialization expression: Initialize the loop counter value
• test condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
• update expression: Increment and decrement the loop counter value
Flowchart
Example:
<?php
for($i=0;$i<3;$i++)//outer loop
{
for($j=0;$j<2;$j++)//inner loop
{
echo "outer loop index:$i,inner loop index:$j<br>";
}
}
?>
Output:
outer loop index:0,inner loop index:0
outer loop index:0,inner loop index:1
outer loop index:1,inner loop index:0
outer loop index:1,inner loop index:1
Page | 13
outer loop index:2,inner loop index:0
outer loop index:2,inner loop index:1
Syntax:
foreach (array_element as value)
{
//code to be executed
}
Flowchart:
Example:
<?php
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $value)
{
echo "$val \n";
}
$arr = array ("Ram", "Laxman", "Sita");
foreach ($arr as $value)
{
echo "$val \n";
}
?>
Output: 10 20 30 40 50 60
Ram Laxman Sita
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
1.break Statements
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop.
If you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the current
flow of the program at the specified condition and program control resumes at the next statements
outside the loop.
Syntax
jump statement;
break;
Flowchart
Example:
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i= =5){
break;
}
}
?>
Output:
1
2
3
4
5
Page | 15
2.continue statement
The PHP continue statement is used to continue the loop. It continues the current flow of the program
and skips the remaining code at the specified condition.
The continue statement is used within looping and switch control structure when you immediately jump
to the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach
loop. The continue statement allows the user to skip the execution of the code for the specified
condition.
Syntax Flowchart
jump-statement;
continue;
Example:
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i= =5){
continue;
}
}
?>
Output:
1
2
3
4
6
7
8
9
10
<?php
// if form submitted
// process form input
} else {
// retrieve number from form input
$num = $_POST['num'];
// check that number is positive
if ($num <= 0) {
echo 'ERROR: Please enter a number greater than 0';
exit();
}
// calculate factorial
// by multiplying the number by all the
// numbers between itself and 1
$factorial = 1;
for ($x=$num; $x>=1; $x--) {
$factorial *= $x;
}
echo "Factorial of $num is: $factorial";
}
?>
</body>
</html>
Output
Page | 17
Output: After swapping:
a =78 b=45
?>
output: 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ,
5.Factorial of a number
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
output: Factorial of 4 is 24
Page | 19
Working with String and Numeric Functions
the language comes with a full-featured library of built-in functions that let you do everything from reversing
and splitting strings to calculating logarithmic values.
Length String
The strlen() function returns the number of characters in a string. Here’s an example of it in action:
<?php
// calculate length of string
$str = 'Welcome to Vedant';
echo strlen($str);
?>
Output: 17
Reversing String
Reversing a string is as simple as calling the strrev() function, as in the next listing:
<?php
// reverse string
$str = 'Vedant BCA College';
echo strrev($str);
?>
Output: egelloC ACB tnadeV
Repeating Strings
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.
Here’s an example:
<?php
// repeat string
$str = 'yo';
Page | 21
echo str_repeat($str, 3);
?>
Output: yoyoyo
NOTE
When using the substr() function, the first character of the string is treated as offset 0, the second character as
offset 1, and so on. To extract a substring from the end of a string (rather than the beginning), pass substr() a
negative offset, as in this revision of the preceding example:
<?php
// extract substring
$str = 'Welcome to Vedant';
echo substr($str, 3, 5). substr($str, -4, 4);
?>
Output: come dant
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);
?>
Output: 0 1
Counting Strings
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
$str = "Welcome to Vedant College";
echo str_word_count($str);
?>
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
Output: 4
Replacing Strings
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 '@' with 'at'
$str = 'vedant@domain.net';
echo str_replace('@', ' at ', $str);
?>
Output: vedant at domain.net
Formatting Strings
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
$str = ' a b c ';
echo trim($str);
?>
Output: 'a b c'
<?php
// change string case
$str = 'Welcome to Vedant College';
echo strtoupper($str);
echo strtolower($str);
?>
Output: WELCOME TO VEDANT COLLEGE
welcome to vedant college
ucwords(): ucwords() function is used to convert first letter of every word into upper case.
ucfirst(): ucfirst() function returns string converting first character into uppercase. It doesn't change the
case of other characters.
lcfirst(): lcfirst() function is used to convert first character into lowercase. It doesn't change the case of
other characters.
<?php
// change string case
$str = ' Welcome to Vedant College'';
Page | 23
echo ucwords($str);
echo ucfirst($str);
echo lcfirst($str):
?>
Output:
Welcome To Vedant College
Welcome to Vedant College
welcome to Vedant College
You can reverse the work done by addslashes() with the apply named stripslashes() function, which removes all
the backslashes from a string.
The htmlentities() and htmlspecialchars() functions automatically convert special HTML symbols (like < and >)
into their corresponding HTML representations (< and &<hairline #>gt;). Similarly, the nl2br() function
automatically replaces newline characters in a string with the corresponding HTML line break tag <br />.
Here’s an example:
<?php
// replace with HTML entities
$html = '<div width="200">This is a div</div>';
echo htmlentities($html);
?>
output: '<div width="200">This is a div</div>'
<?php
// replace line breaks with <br/>s
$lines = 'This is a bro
ken line';
echo nl2br($lines);
?>
output: 'This is a bro<br />ken line'
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)
You can reverse the effect of the htmlentities() and htmlspecialchars()functions with the html_entity_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
// strip HTML tags from string
$html = '<div width="200">Please <strong>log in again</strong></div>';
echo strip_tags($html);
?>
output: 'Please log in again'
Page | 25
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
$num = 19.7;
// round number up
echo floor($num);
// output: 19
echo round($num);
// output: 20
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 log of 100, base 10
// output: 2
echo log(100,10);
// calculate exponent of 2.30258509299
// output: 9.99999999996
echo exp(2.30258509299);
?>
// convert to hexadecimal
// output: 8
echo dechex(8);
// convert to octal
// output: 10
echo decoct(8);
Page | 27
Unit 2 Assignment Questions
2marks questions
1. Difference between if statement and if else statement.
2. Difference between while and do while statements.
3.What is Conditional Statements?
4.What is Loop?
4.What are the String function?
5.Mention any two numeric functions and their use.
6.What are the simple conditional statements.
7.What are the complex conditional statements.
8.Write the syntax of switch case.
9.What are the numeric function?
10.difference between break statement and continue statement.
11.What are the HTML string function.
5 Marks Questions
1.What are string functions in PHP?Discribe common functions with an example.
2. Describe the concept of nested conditional statements and provide a PHP example to
demonstrate how they are used.
3. Described while and do…while loop in PHP.
4.Explain Simple Conditional Statements with an example.
5.Explain Complex Conditional Statements with an example
6.Write a program to generate prime numbers between given two number(range)
7.Write a PHP script to implement simple calculator operation
8.Write a program to demonstrate string manipulation functions.
9.Explian the numeric function.
10.Explain the HTML string function.