0% found this document useful (0 votes)
28 views28 pages

UNIT 2 PHP and MYSQL (Controlling Program Flow)

This document covers Unit 2 of a PHP and MySQL course, focusing on controlling program flow through conditional statements, loops, and string functions. It explains simple and complex conditional statements, including if, if-else, switch-case, and nested if statements, as well as various types of loops such as while, do-while, for, and foreach. Additionally, it discusses interrupting and skipping loops using break and continue statements.
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)
28 views28 pages

UNIT 2 PHP and MYSQL (Controlling Program Flow)

This document covers Unit 2 of a PHP and MySQL course, focusing on controlling program flow through conditional statements, loops, and string functions. It explains simple and complex conditional statements, including if, if-else, switch-case, and nested if statements, as well as various types of loops such as while, do-while, for, and foreach. Additionally, it discusses interrupting and skipping loops using break and continue statements.
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/ 28

College:Vedanth BCA and Bcom College,Vijayapura

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.

Controlling Program Flow/Decision Making


 They accepted one or more input values, performed calculations or comparisons with them, and returned
a result. In reality, though, PHP programs are never so simple: most programs will need to make
complex decisions and execute different operations at run time in accordance with programmer-
specified conditions.

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

Writing Simple Conditional Statements


A conditional statement in PHP is a programming construct that allows you to execute different blocks of
code based on whether a specified condition evaluates to true or false. It enables you to create dynamic and
flexible code logic by controlling the flow of execution based on various conditions.

Simple Conditional Statements are


1. if Statement
2. if else Statement

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";
} }
?> ?>

Output: 12 is less than 100 Output: The number is positive

2.if else Statements:


 You can enhance the decision making process by providing an alternative choice through adding an else
statement to the if statement.
 The if...else statement allows you to execute one block of code if the specified condition is evaluates to
true and another block of code if it is evaluates to false.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

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

Write a PHP Program to Testing Odd and Even Numbers


File Name: oddeven.php
<!DOCTYPE html>
<html>
<head>
<title>Odd/Even Number Tester</title>
</head>

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)

Writing More Complex Conditional Statements


The if-else statement lets you define actions for two eventualities: a true condition and a false condition. In
reality, however, your program may have more than just these two simple outcomes to contend with.
For these situations, PHP offers two constructs that allow the programmer to account for multiple possibilities:
1.the if-else if-else statement
2.the switch-case statement.

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)

Output: Happy Independence Day!!!

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 switch statement with String


PHP allows to pass string in switch expression. Let's see the below example of course duration by passing string
in switch case statement.

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

Output: BCA is 3 years course

Combining Conditional Statements/Nested if Statement


The nested if statement contains the if block inside another if block. The inner if statement executes only when
specified condition in outer if statement is true.
Syntax
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

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”;
}
}
?>

Output: 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

1.The while Loop


 The easiest type of loop to understand is the while loop, which repeats continuously while a pre
specified condition is true.
 Notice the condition enclosed in parentheses; so long as this condition evaluates to true, the code within
the curly braces is executed. As soon as the condition becomes false, the loop stops repeating

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)

2.The do-while Loop


This is an exit control loop which means that it first enters the loop, executes the statements, and then checks
the condition. Therefore, a statement is executed at least once on using the do…while loop. After executing
once, the program is executed as long as the condition holds true.

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.

3.The for Loop


This type of loops is used when the user knows in advance, how many times the block needs to execute. These
type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the
initialization, the test condition and the counter.

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:

Example: which lists the numbers between 1 and 10:


<?php
// repeat continuously until counter becomes 10
// output:
for ($x=1; $x<10; $x++)
{
echo "$x ";
}
?>

Output: 1 2 3 4 5 6 7 8 9

4.Combining Loops(Nested for loops)


 The method of using the for loop inside another for loop.
 It first performs a single iteration for the parent for loop and executes all the iterations of the inner loop.
After that it again checks the parent iteration and again performs all the iteration of inner loop.
Syntax
for (initialization expression; test condition; update expression)
{
for (initialization expression; test condition; update expression)
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

{
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

.The foreach loop


The foreach statement is used to loop through arrays. For each pass the value of the current array element is
assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

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)

Interrupting and Skipping Loops


it’s interesting to discuss two PHP statements that allow you to either interrupt a loop or skip a particular
iteration of a loop.There are two different types
1.break Statements
2.continue Statements

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

Simple program to building a Factorial Calculator


<html>
<head>
<title> Factorial Calculator</title>
</head>
<body>
<h2>Factorial Calculator</h2>
<?php
// if form not yet submitted
// display form
if (!isset($_POST['submit']))
{
?>
<form method="post" action="factorial.php">
Enter a number: <br />
<input type="text" name="num" size="3" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

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

PHP Simple programs

1.swapping Using Third Variable


<?php
$a = 45;
$b = 78;
// Swapping Logic
$third = $a;
$a = $b;
$b = $third;
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b;
?>

Page | 17
Output: After swapping:
a =78 b=45

2. Swapping Without using Third Variable(+ and -):


<?php
$a=234;
$b=345;
//using arithmetic operation
$a=$a+$b;
$b=$a-$b;
$a=$a-$b;
echo "Value of a: $a</br>";
echo "Value of b: $b</br>";
?>
Output:Value of a: 345
Value of b: 234

3. Example for (* and /):


<?php
$a=234;
$b=345;
// using arithmetic operation
$a=$a*$b;
$b=$a/$b;
$a=$a/$b;
echo "Value of a: $a</br>";
echo "Value of b: $b</br>";
?>
Output:Value of a: 345
Value of b: 234

4. PHP script for generating a list of prime numbers below 100.


<?php
$number = 2 ;
while ($number < 100 )
{
$div_count=0;
for ( $i=1;$i<=$number;$i++)
{
if (($number%$i)==0)
{
{
$div_count++;
}
}
if ($div_count<3)
{
echo $number." , ";
}
$number=$number+1;
}
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

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

6.Palindrome Number Program Without of Using PHP Predefined Function :


<?php
$number = 53235;
$p = $number;
$revnum =0;
while($number != 0)
{
$revnum = $revnum*10 + $number % 10 ;
$number = (int)($number/10);
}
if($revnum==$p)
echo $p.' is palindrome number';
else
echo 'number is not palindrome';
?>
Output:53235 is palindrome number

7.Reversing Number in PHP


<?php
$num = 23456;
$revnum = 0;
while ($num > 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}
echo "Reverse number of 23456 is: $revnum";
?>
Output:Reverse number of 23456 is: 65432

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.

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. Table 3-3 lists some of these functions.
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

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);
// output: true
$str = '0';
echo (boolean) empty($str);
// output: true
unset($str);
echo (boolean)empty($str);
?>
Output:1 1 1 1

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

Working with Substrings


PHP also allows you to slice a string into smaller parts with the substr() function, which accepts three
arguments: the original string, the position (offset) at which to start slicing, and the number of characters to
return from the starting position. The following listing illustrates this in action:
<?php
// extract substring
// output: 'come'
$str = 'Welcome to vedant';
echo substr($str, 3, 4);
?>
Output: come

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'

Upper and Lower String


 strtoupper(): PHP strtoupper() function is used to convert lowercase latter into uppercase latter.
 strtolower(): strtolower() function is used to convert uppercase latter into lowercase latter.

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

Working with HTML Strings


PHP also has some functions exclusively for working with HTML strings. First up, the addslashes() function,
which automatically escapes special characters in a string with backslashes. Here’s an example:
<?php
// escape special characters
$str = "You're awake, aren't you?";
echo addslashes($str);
?>
output: 'You\'re awake, aren\'t you?'

You can reverse the work done by addslashes() with the apply named stripslashes() function, which removes all
the backslashes from a string.

Consider the following example, which illustrates:


<?php
// remove slashes
// output: 'John D'Souza says "Catch you later".'
$str = "John D\'Souza says \"Catch you later\".";
echo stripslashes($str);
?>

The htmlentities() and htmlspecialchars() functions automatically convert special HTML symbols (like < and >)
into their corresponding HTML representations (&lt; 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: '&lt;div width=&quot;200&quot;&gt;This is a div&lt;/div&gt;'

<?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'

Using Numeric Functions


the language has over 50 built-in functions for working with numbers, ranging from simple formatting functions
to functions for arithmetic, logarithmic, and trigonometric manipulations. Table 3-4 lists some of these
functions.

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

// round number down


echo ceil($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);
?>

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 example illustrates:
<?php
College:Vedanth BCA and Bcom College,Vijayapura
Lecture:Annapoorna Kalloli
Subject:PHP and MySQL(Unit 2)

// generate a random number


echo rand();
// generate a random number between 10 and 99
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
// 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);
?>

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy