0% found this document useful (0 votes)
17 views23 pages

PHP Control Flow: Conditionals & Loops

Unit II covers controlling program flow in PHP through conditional statements, loops, and unconditional statements. It explains various types of conditional statements such as if, switch, and ternary operators, as well as different loop types like while, for, and foreach. Additionally, it discusses string and numeric functions for manipulating data in PHP.

Uploaded by

sakthi98076
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)
17 views23 pages

PHP Control Flow: Conditionals & Loops

Unit II covers controlling program flow in PHP through conditional statements, loops, and unconditional statements. It explains various types of conditional statements such as if, switch, and ternary operators, as well as different loop types like while, for, and foreach. Additionally, it discusses string and numeric functions for manipulating data in PHP.

Uploaded by

sakthi98076
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

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


Controlling program flow in PHP refers to altering the
sequential execution of statements based on conditions or for
repetitive tasks
Control flow refers to the order in which statements within a
program execute.
PHP provides several control structures for controlling program
flow, such as:
1. Conditional Statements
2. Loops
3. Jump Statements
The classification of control flow statements in PHP is illustrated
in the below figure
Conditional Statements
Conditional statement in PHP are those statements that are
used to make decisions and execute specific blocks of code
based on the conditions. PHP supports several types of
conditional statements:
1. If statement
2. If-else statement
3. Nested If statement
4. If-elseif-else statement
5. Switch statement
6. Conditional (or)Ternary Operators

1. if Statement
The if statement is the simplest form of decision making.
It executes a block of code if the specified condition is true. If
the condition is false, the block of code is skipped.

Syntax:

if (condition)
{
// if TRUE then execute this code
}
Example:
<?php
$x = 12;

if ($x > 0)
{
echo "The number is positive";
}
?>

Output
The number is positive

2. if...else Statement
This statement executes a block of code if the specified
condition is true, and executes another block of code if the
condition is false.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
Example:
<?php
$x = -12;
if ($x > 0) {
echo "The number is positive";
}
else{
echo "The number is negative";
}
?>

Output:
The number is negative
( write this for Complex Conditional Statements)
3. 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 (condition1)
{ //code to be executed if condition is true
if (condition2)
{ //code to be executed if condition is true
}
}
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


[Link]-elseif-else statement
The if-else-if else is a special statement used to combine
multiple if ..else statements.
When need to check multiple conditions then this structure if-
elseif-else ladder is used
This structure allows us to check multiple conditions in
sequence.
The first condition that evaluates to true will execute its
corresponding block of code, and all other conditions will be
skipped.
Syntax:
if (condition) {
// 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
}
Example:

<?php
$x = "August";

if ($x == "January") {
echo "Happy Republic Day";
}
elseif ($x == "August") {
echo "Happy Independence Day!!!";
}
else{
echo "Nothing to show";
}
?>

Output

Happy Independence Day!!!

[Link] statement:

The switch statement is used to select one of many blocks of


code to be executed.

Syntax

switch (variable)
{
case value1:
// Code to be executed if the variable equals value1
break;
case value2:
// Code to be executed if the variable equals value2
break;
default:
// Code to be executed if no cases match
}

• The expression is evaluated once


• The value of the expression is compared with the values
of each case
• If there is a match, the associated block of code is
executed
• The break keyword breaks out of the switch block
• The default code block is executed if there is no match

Flow chart:

Example:

<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

Your favorite color is red!

6. Conditional (or)Ternary Operators

The ternary operator (?:) is a conditional operator used to


perform a simple comparison operation.

It provides shorthand way to perform conditional checks.

It generally looks like this:

Syntax

(condition) ? if TRUE execute this : otherwise execute this;

Example:
<?php
$age = 20;
echo ($age >= 18) ? "You are an adult." : "You are a minor.";
?>

Output:
You are an adult.
Repeating Action with Loops

Loops are used to execute the same block of code


again and again, as long as a certain condition is
true.

In PHP, we have the following loop types:

1. while loop

2. do-while loop

3. for loop

4. foreach loop

(1) while loop:

The while loop executes a block of code as long as the


specified condition is true.

Syntax
while (condition is true)
{
code to be executed;
}

FLOWCHART:
Example: Printing numbers from 1 to 5.
<?php
$num = 1;
while ($num <= 5) {
echo $num . "\n";
$num++;
}
?>

Output
1
2
3
4
5

(2) do-while loop:

The do-while loop is similar to the while loop, but it


executes the code block at least once before the checking
the specified condition.

The do-while loop is an exit control loop, which means, it


first enters the loop, executes the statements, and then
checks the condition.

Syntax
do {
// Code is executed
} while ( condition );

FLOWCHART
<?php
$i = 10;
$sum = 0;
do{
$sum = $sum + $i;
$i++;
}
while ($i < 6);
echo $sum;
?>

The output of the above code will be:

10

(3) for loop:

The for loop executes a block for a specific number of


times.
It is used when the number of iterations is known in
advance.

Syntax

for (initialization; condition; increment)


{
code to be executed;

}
• The initialization is evaluated once when the loop
starts.
• The condition is evaluated once in each iteration. If
the condition is true, the statement in the body is
executed. Otherwise, the loop ends.
• The increment expression is evaluated once after each
iteration.

Example: Print the numbers from 1 to 5

<?php
for ($i = 1; $i <= 5; $i++) {
echo $i."\n";
}
?>

The output of the above code will be:


1
2
3
4
5
(4) foreach loop :

• foreach loop is specially designed to access all the


elements of an array in the fastest and the easiest
way.
• foreach works only on arrays and objects

Syntax

foreach($array as $variable)

{
statements;
}

• Foreach : The foreach loop runs for all elements of an


array. It starts with the first element and ends with
the last one.
• $array : $array is the array variable given by array
expression.
• $variable: $variable specifies that for every loop the
value of the current element is assigned to $variable.

Example:

<?php
$x=array("1","2","3","4");
foreach ($x as $value)
{
echo $value . "<br />";
}
?>

• Here in PHP, $x=array("1","2","3","4") specify that to


value of the current array element is assigned to $value.
• Here, foreach ($x as $value) specify an array pointer is
moved by one, until it reaches the last array element.

Output: the array element 1,2,3,4 will be printed until it


reaches the last array element “4”.
Unconditional Statements

An unconditional statement is a programming statement


that transfers control of the program to another location
without checking any conditions.

PHP language supports four types of unconditional statements.


They are as follows:
• Break statement
• Continue statement
• Return
• Goto

1. break

It Exits from a loop or switch statement immediately


When break is encountered, the program immediately exits the
enclosing for, foreach, while, do..while, or switch block

<?php

for ($i = 0; $i < 10; $i++) {


if ($i == 5)
{
break;
}
echo $i . " ";
}

?>

Output: 0 1 2 3 4

2. Continue Statement:

The PHP continue keyword is used to halt the current iteration


of a loop but it does not terminate the loop
The continue statement in PHP let the program skip a block of
codes for current iteration in a loop.
Example:
<? php
for ($i = 0; $i < 5; $i++) {
if ($i == 2) {
continue;
}
echo $i . " ";
}
?>
Output: 0 1 3 4

3. return

Ends the execution of a function and optionally returns a value.

Example:
<? php
function add($a, $b)
{
return $a + $b;
}

echo add(5, 3);

?>

Output: 8

4. goto

The goto statement is another unconditional control statement


used to jump to another section of the code.

Jumps to a specified label within the same file.


Syntax:
goto label;

// some code...

label:
// code to execute after jump
Example:

<? php

$i = 0;

goto skip;

echo "This will not be printed.";

skip:
echo "This will be printed.";

?>

Output: This will be printed.

Working with String and Numeric Functions

Strings
String in PHP is a set of characters.
In PHP string can be created using either single quote or double quote.
Single Quote Vs Double Quote String.
$str1 = 'This is string example within single quote';
$str2 = "This is string example within double quote";
String written inside double quote will replace the variable values if any
whereas single quote string will print the string as it is.
Example.
<?php
$name = 'PHP';
echo 'This is $name'; // output : This is $name.
echo "This is $name"; // output : This is PHP.
?>

String functions

String functions allow manipulation and analysis of text data.


The following are some string functions in php
Function Description Example

strlen() Returns the <?php


length of a echo strlen("Hello PHP!"); ?>
string
output:10

strtolower() Converts a <?php


string to echo strtolower("LOWERCASE");
lowercase ?>
output:lowercase

strtoupper() Converts a <?php


string to echo strtoupper("uppercase");
uppercase ?>

Output:UPPERCASE

strrev() Reverses a <?php


String echo strrev("Hello PHP!");
?>

Output: !PHP olleH

substr() Extracts part of <?php


a string echo substr("abcdef", 1, 3) ;
?>
Output: bcd
strpos() Finds position <?php
of first echo strpos("Hello PHP!", "PHP");
occurrence of a ?>
substring output: 6

str_replace() Replaces text <?php


within a string echo
str_replace("world","Peter","Hello
world!");
?>
Output: Hello Peter
trim() Removes <?php
whitespace echo trim(" hello ");
from the ?>
beginning and Output: hello
end

word_count() Count The <?php echo


Number of str_word_count("Hello PHP!"); ?>
Words in a
String Output: 2

ucwords() Capitalize the <?php


first letter of echo ucwords("it should be in
each word uppercase");
?>

Output: It Should Be In
Uppercase

Numeric functions

• Numeric functions in PHP are built-in functions


used to perform mathematical or numerical
operations on numbers (integers or floats).
• These functions are part of PHP’s Math Library

• The following specifies the list PHP of math


functions
Function Description Example
pi() returns the value of <?php
PI echo(pi());
?>
Output: 3.1415926535898
abs() Returns absolute <?php
value echo(abs(-11.25));
?>
Output: 11.25
ceil() Rounds up to the <?php
nearest integer echo (ceil(4.3));
?>
Output: 5
floor() Rounds down to <?php
the nearest integer echo (floor(4.9));
?>
Output: 4
round() Rounds a number <?php
to the nearest echo(round(0.74));
integer echo(round(0.44));
?>
Output:
1
0
max() Returns the highest <?php
value echo(max(0, 300, 49, 110,
-88, -200));
?>
Output: 300
min() Returns the lowest <?php
value echo(min(0, 250, 49, 110, -
88, -200));
?>
output: -200
rand() Generates a <?php
random number echo(rand());
?>
Output: 944034960
sqrt() Returns square <?php
root echo(sqrt(36));
?>
Output:6
is_numeric() Checks if a variable <?php
is a number or echo(is_numeric("123"));
numeric string ?>
Output: true

You might also like