PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
PHP Tutorial
Unit II: Controlling Program Flow
Topics Covered
1. Writing Simple Conditional Statements
2. Writing More Complex Conditional Statements
3. Repeating Actions with Loops
4. Working with String and Numeric Functions
SECTION 1: Writing Simple Conditional Statements
1. Decision-Making in PHP
Decision-making is an important part of programming, allowing the program to execute
different actions based on conditions. In PHP, decision-making helps control the flow of a
program by executing different blocks of code depending on certain conditions or expressions.
PHP provides several constructs for decision-making, including if, else, elseif, and switch.
These control structures can be used to make logical decisions in a program.
1.1 The if Statement
The if statement is the simplest form of decision making. It executes a block of code if the
specified condition evaluates to true. If the condition evaluates to 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"
Unit II Notes | Page 1 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
1.2 The if...else Statement
The if-else statement is an extension of the if statement. It allows you to specify an alternative
block of code that is executed when the condition is false. This is useful when there are two
mutually exclusive conditions.
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"
Comparison Operators Used in Conditions
Operator Meaning Example Result
== Equal (loose) $a == $b true if values are
equal
=== Identical (strict) $a === $b true if values AND
types are equal
!= Not equal $a != $b true if values differ
!== Not identical $a !== $b true if value OR
type differs
> Greater than $a > $b true if $a is greater
< Less than $a < $b true if $a is smaller
>= Greater or equal $a >= $b true if $a >= $b
<= Less or equal $a <= $b true if $a <= $b
Unit II Notes | Page 2 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
Logical Operators Used in Conditions
Operator Name Description Example
&& AND Both conditions $a > 0 && $b > 0
must be true
|| OR At least one $a > 0 || $b > 0
condition must be
true
! NOT Negates the !($a > 0)
condition
and AND (alt) Same as && but $a > 0 and $b > 0
lower precedence
or OR (alt) Same as || but $a > 0 or $b > 0
lower precedence
SECTION 2: Writing More Complex Conditional Statements
2. Complex Conditional Statements
2.1 The if...elseif...else Statement
In scenarios where you need to evaluate multiple conditions, you can use the if-elseif-else
ladder. This construct allows you 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 (condition1) {
// if condition1 is TRUE
} elseif (condition2) {
// if condition2 is TRUE
} elseif (condition3) {
// if condition3 is TRUE
} else {
// if none are TRUE
}
Example: Checking month for national holidays
<?php
$x = "August";
if ($x == "January") {
echo "Happy Republic Day";
} elseif ($x == "August") {
echo "Happy Independence Day!!!";
Unit II Notes | Page 3 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
} else {
echo "Nothing to show";
}
?>
Output: "Happy Independence Day!!!"
Example: Grade classification
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Needs Improvement";
}
?>
Output: "Grade: B"
2.2 Nested if Statements
Sometimes, you need to check a condition inside another condition. This is where nested if
statements are useful. PHP allows if statements to be placed inside other if statements.
Example: Checking role and active status
<?php
$role = "admin";
$active = true;
if ($role == "admin") {
if ($active) {
echo "Admin access granted.";
} else {
echo "Admin account is inactive.";
}
}
?>
Output: "Admin access granted."
2.3 The switch Statement
The switch statement performs matching against multiple cases. It first evaluates an
expression and then compares it with the values of each case. If a case matches, then that
case block is executed. The switch statement is a cleaner alternative to long if...elseif...else
ladders when checking a single variable against multiple possible values.
Unit II Notes | Page 4 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
Two Key Keywords in switch
break — stops execution from falling through to the next case
default — runs if none of the cases match (similar to else)
Syntax:
switch (variable) {
case value1:
// Code if variable == value1
break;
case value2:
// Code if variable == value2
break;
default:
// Code if no cases match
}
Example: Day of week
Code Output
<?php Start of the week!
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the
week!";
break;
case "Friday":
echo "End of the week!";
break;
case "Saturday":
case "Sunday":
echo "Weekend!";
break;
default:
echo "Mid-week!";
}
?>
switch vs if-elseif Comparison
Feature switch if-elseif-else
Best for Single variable, many Different variables,
values complex expressions
Comparison type Loose (== by default) Any comparison operator
Unit II Notes | Page 5 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
Fall-through Yes (use break to prevent) No — only first true block
runs
default/else default keyword else clause
Readability Cleaner for multiple fixed More flexible for range
values checks
2.4 The Ternary Operator
PHP provides a shorthand way to perform conditional checks using the ternary operator (?:).
This operator allows you to write simple if-else conditions in a compact form. It is called
'ternary' because it takes three operands: a condition, a result for true, and a result for false.
Syntax: (condition) ? value_if_true : value_if_false;
Example:
<?php
$age = 20;
echo ($age >= 18) ? "You are an adult." : "You are a minor.";
?>
Output: "You are an adult."
Example: Nested ternary for grades
<?php
$points = 75;
echo $points >= 90 ? "A" : ($points >= 75 ? "B" : "C");
?>
Output: "B"
2.5 The Null Coalescing Operator (??)
Introduced in PHP 7, the null coalescing operator (??) returns the first operand if it exists and
is not null, otherwise it returns the second operand. It is perfect for providing fallback values,
especially with $_GET, $_POST, or optional data.
Syntax: $result = $variable ?? 'default_value';
Example:
<?php
$username = $_GET['user'] ?? 'Guest';
echo "Hello, " . $username . "!";
?>
If 'user' is not passed in the URL query string, $username defaults to 'Guest'.
Unit II Notes | Page 6 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
SECTION 3: Repeating Actions with Loops
3. PHP Loops
In PHP, loops are used to repeat a block of code multiple times based on a given condition.
Loops allow you to execute a block of code multiple times without rewriting the code. This is
useful when working with repetitive tasks, such as iterating through arrays or data structures,
performing an action a specific number of times, or waiting for a condition to be met.
Types of Loops in PHP
1. for loop — used when the number of iterations is known
2. while loop — entry-control loop; checks condition before executing
3. do-while loop — exit-control loop; executes at least once
4. foreach loop — designed specifically for iterating over arrays
3.1 The for Loop
The PHP for loop is used when you know exactly how many times you want to iterate through
a block of code. It consists of three expressions: Initialization (sets the initial value), Condition
(checks if the loop should continue), and Increment/Decrement (changes the loop variable
after each iteration).
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example: Printing numbers 1 to 5
Code Output
<?php 1
for ($num = 1; $num <= 5; $num++) 2
{ 3
echo $num . "\n"; 4
} 5
?>
Example: Sum of first N numbers
<?php
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
Unit II Notes | Page 7 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
}
echo "Sum = " . $sum; // Output: Sum = 55
?>
Parts of the for Loop
Part Position Purpose Example
Initialization First expression Sets the starting $i = 0
value of the
counter
Condition Second Evaluated before $i <= 10
expression each iteration; loop
runs while true
Increment/ Third expression Updates the $i++ or $i--
Decrement counter after each
iteration
Body Inside { } Code executed on echo $i;
each iteration
3.2 The while Loop
The while loop is an entry-control loop. It first checks the condition at the start of the loop; if it is
true, then it enters the loop and executes the block of statements. It continues executing as
long as the condition remains true. If the condition is false from the start, the loop body never
executes.
Syntax:
while (condition) {
// Code to be executed
}
Code Output
<?php 1
$num = 1; 2
while ($num <= 5) { 3
echo $num . "\n"; 4
$num++; 5
}
?>
3.3 The do...while Loop
The do-while loop is an exit-control loop. This means it first enters the loop, executes the
statements, and then checks the condition. Therefore, the body of a do-while loop is always
Unit II Notes | Page 8 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
executed at least once — even if the condition is initially false. After executing once, the loop
continues as long as the condition remains true.
Syntax:
do {
// Code to be executed
} while (condition);
Code Output
<?php 1
$num = 1; 2
do { 3
echo $num . "\n"; 4
$num++; 5
} while ($num <= 5);
?>
Key Difference: The do-while loop runs at least once even if the condition is false from the
start — unlike while and for loops.
3.4 The foreach Loop
The foreach loop is specifically designed to iterate over arrays. For every counter of the loop,
an array element is assigned to a variable, and execution moves to the next element. It
simplifies working with arrays and objects by automatically iterating through each element
without requiring a manual index counter.
Syntax (values only):
foreach ($array as $value) {
// Use $value
}
Syntax (keys and values):
foreach ($array as $key => $value) {
// Use $key and $value
}
Example: Iterating an indexed array
Code Output
<?php 10 20 30 40 50
$arr = array(10, 20, 30, 40, 50);
foreach ($arr as $val) {
echo $val . " ";
}
Unit II Notes | Page 9 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
?>
Example: Iterating an associative array
Code Output
<?php Anjali => 25
$ages = array("Anjali" => 25, Kriti => 30
"Kriti" => 30, Ayushi => 22
"Ayushi" => 22);
foreach ($ages as $name => $age)
{
echo $name . " => " . $age .
"\n";
}
?>
3.5 Loop Control Statements
PHP provides two special statements that can alter the normal execution flow of a loop: break
and continue.
break: Immediately exits the loop, regardless of the loop condition.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) break; // stop when i reaches 6
echo $i . " ";
}
// Output: 1 2 3 4 5
?>
continue: Skips the rest of the current iteration and proceeds to the next one.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) continue; // skip even numbers
echo $i . " ";
}
// Output: 1 3 5 7 9
?>
Loop Comparison Summary
Loop Type Condition Check Minimum Best Used For
Executions
Unit II Notes | Page 10 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
for Before each 0 (if condition false) Known number of
iteration iterations
while Before each 0 (if condition false) Unknown
iteration iterations,
condition-based
do...while After each iteration 1 (always runs Must run at least
once) once
foreach Internally (array- 0 (if array is empty) Iterating
based) arrays/collections
SECTION 4: Working with String and Numeric Functions
4. PHP String Functions
Strings are a collection of characters. For example, 'G' is a character and 'GeeksforGeeks' is a
string. PHP provides a rich set of built-in string functions. These functions are part of the PHP
core and do not require any additional installation.
4.1 String Length and Case Functions
Function Description Example Output
strlen($str) Returns the length strlen("Hello") 5
of a string
strtolower($str) Converts string to strtolower("HELLO") "hello"
lowercase
strtoupper($str) Converts string to strtoupper("hello") "HELLO"
uppercase
ucfirst($str) Capitalizes the first ucfirst("hello world") "Hello world"
character
lcfirst($str) Lowercases the lcfirst("HELLO") "hELLO"
first character
ucwords($str) Capitalizes first ucwords("hello "Hello World"
letter of each word world")
4.2 String Search and Position Functions
Function Description Returns
strpos($str, $find) Position of first occurrence Integer position or false
(case-sensitive)
stripos($str, $find) Position of first occurrence Integer position or false
(case-insensitive)
Unit II Notes | Page 11 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
strrpos($str, $find) Position of last occurrence Integer position or false
(case-sensitive)
strripos($str, $find) Position of last occurrence Integer position or false
(case-insensitive)
strstr($str, $find) Returns portion from first Substring or false
match onward
stristr($str, $find) Case-insensitive version of Substring or false
strstr()
strrchr($str, $char) Returns portion from last Substring or false
occurrence of char
Example: Using strpos()
<?php
$str = "Hello World";
$pos = strpos($str, "World");
echo $pos; // Output: 6
?>
4.3 String Replacement and Modification
Function Description Example
str_replace($search, Replaces all occurrences str_replace("World",
$replace, $str) of search in string "PHP", "Hello World")
str_ireplace() Case-insensitive version of
str_replace()
substr($str, $start, $length) Returns a portion of a substr("Hello World", 6, 5)
string // "World"
strrev($str) Reverses a string strrev("Hello") // "olleH"
str_repeat($str, $n) Repeats string n times str_repeat("ab", 3) //
"ababab"
str_pad($str, $length) Pads string to a given str_pad("5", 3, "0",
length STR_PAD_LEFT) // "005"
wordwrap($str, $width) Wraps string at given
width
strtr($str, $from, $to) Replaces characters
Example: Using str_replace()
<?php
$str = "Hello World";
echo str_replace("World", "PHP", $str);
// Output: Hello PHP
?>
Unit II Notes | Page 12 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
Example: Using substr()
<?php
$str = "Hello World";
echo substr($str, 6, 5);
// Output: World
?>
4.4 String Trimming Functions
Function Description
trim($str) Removes whitespace from both ends of a
string
ltrim($str) Removes whitespace from the left
(beginning) of a string
rtrim($str) / chop($str) Removes whitespace from the right (end)
of a string
Example:
<?php
$str = " Hello World ";
echo trim($str); // "Hello World"
echo ltrim($str); // "Hello World "
echo rtrim($str); // " Hello World"
?>
4.5 String Split and Join Functions
Function Description Example
explode($delimiter, $str) Splits a string into an array explode(",", "a,b,c") →
by delimiter ["a","b","c"]
implode($glue, $array) / Joins array elements into a implode(", ", ["a","b"]) →
join() string "a, b"
str_split($str, $len) Splits string into array of str_split("Hello", 2) →
characters/chunks ["He","ll","o"]
chunk_split($str, $len, Splits string into smaller
$end) chunks
strtok($str, $delimiters) Tokenizes a string
Example: Using explode() and implode()
<?php
$csv = "apple,banana,cherry";
$arr = explode(",", $csv);
Unit II Notes | Page 13 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
print_r($arr);
// Array ( [0] => apple [1] => banana [2] => cherry )
$back = implode(" | ", $arr);
echo $back;
// apple | banana | cherry
?>
4.6 String Comparison Functions
Function Description Returns
strcmp($s1, $s2) Case-sensitive binary 0 if equal, negative or
string comparison positive int
strcasecmp($s1, $s2) Case-insensitive string 0 if equal, negative or
comparison positive int
strncmp($s1, $s2, $n) Compares first n 0 if equal
characters (case-sensitive)
strncasecmp($s1, $s2, $n) Compares first n 0 if equal
characters (case-
insensitive)
similar_text($s1, $s2) Returns number of Integer count
matching characters
levenshtein($s1, $s2) Computes edit distance Integer distance
between two strings
4.7 Other Useful String Functions
Function Description
str_word_count($str) Returns count of words in a string
nl2br($str) Inserts HTML <br> tags before each
newline
strip_tags($str) Removes HTML and PHP tags from a
string
addslashes($str) Adds backslashes before special
characters
stripslashes($str) Removes backslashes from a string
htmlspecialchars($str) Converts special HTML characters to
entities
ord($char) Returns the ASCII value of a character
chr($ascii) Converts ASCII value to a character
md5($str) Returns the MD5 hash of a string
Unit II Notes | Page 14 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
sha1($str) Returns the SHA-1 hash of a string
number_format($num, $dec) Formats a number with grouped
thousands and decimals
sprintf($format, ...) Returns a formatted string
Example: Commonly used string utilities
<?php
echo str_word_count("Hello World PHP"); // 3
echo ord("A"); // 65
echo chr(65); // A
echo md5("password"); // 5f4dcc3b5aa...
echo number_format(1234567.891, 2); // 1,234,567.89
?>
5. PHP Numeric (Math) Functions
The predefined math functions in PHP are used to handle mathematical operations within
integer and float types. These functions are part of the PHP core and do not require any
installation.
5.1 Basic Arithmetic Functions
Function Description Example Output
abs($n) Returns absolute abs(-15) 15
(positive) value
ceil($n) Rounds up to ceil(4.3) 5
nearest integer
floor($n) Rounds down to floor(4.9) 4
nearest integer
round($n, $dec) Rounds to nearest round(4.567, 2) 4.57
value / decimal
places
fmod($x, $y) Floating-point fmod(10.5, 3.5) 0
modulo (remainder)
intdiv($a, $b) Integer division intdiv(7, 2) 3
(truncated quotient)
pow($base, $exp) Base raised to the pow(2, 8) 256
power of exponent
sqrt($n) Square root of a sqrt(144) 12
number
hypot($x, $y) Hypotenuse of a hypot(3, 4) 5
Unit II Notes | Page 15 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
right triangle
Example:
<?php
echo abs(-42); // 42
echo ceil(4.1); // 5
echo floor(4.9); // 4
echo round(4.567, 2); // 4.57
echo pow(2, 10); // 1024
echo sqrt(81); // 9
?>
5.2 Maximum, Minimum, and Range
Function Description Example Output
max($a, $b, ...) Returns the max(3, 7, 2) 7
maximum value
min($a, $b, ...) Returns the min(3, 7, 2) 2
minimum value
max($array) Maximum value in max([4,1,9]) 9
an array
min($array) Minimum value in min([4,1,9]) 1
an array
5.3 Random Number Functions
Function Description Example
rand() Generates a random rand()
integer
rand($min, $max) Random integer between rand(1, 100)
min and max
mt_rand($min, $max) Faster Mersenne Twister mt_rand(1, 6)
random integer
srand($seed) Seeds the random number srand(42)
generator
Example: Simulating a dice roll
<?php
$roll = rand(1, 6);
echo "You rolled: " . $roll;
?>
Unit II Notes | Page 16 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
5.4 Logarithm and Exponential Functions
Function Description
log($n) Natural logarithm (base e) of n
log($n, $base) Logarithm of n to specified base
log10($n) Base-10 logarithm of n
exp($n) e raised to the power of n (e^n)
expm1($n) e^n - 1 (more accurate for small n)
5.5 Trigonometric Functions
Function Description
sin($rad) Sine of angle in radians
cos($rad) Cosine of angle in radians
tan($rad) Tangent of angle in radians
asin($n) Arc sine — returns radians
acos($n) Arc cosine — returns radians
atan($n) Arc tangent — returns radians
atan2($y, $x) Arc tangent of two variables
sinh($n) Hyperbolic sine
cosh($n) Hyperbolic cosine
tanh($n) Hyperbolic tangent
deg2rad($deg) Converts degrees to radians
rad2deg($rad) Converts radians to degrees
pi() Returns the value of π (3.14159...)
5.6 Number Base Conversion Functions
Function Description Example Output
decbin($n) Decimal to binary decbin(12) "1100"
bindec($str) Binary to decimal bindec("1100") 12
dechex($n) Decimal to dechex(255) "ff"
hexadecimal
hexdec($str) Hexadecimal to hexdec("ff") 255
decimal
decoct($n) Decimal to octal decoct(8) "10"
octdec($str) Octal to decimal octdec("10") 8
base_convert($n, Convert between base_convert("ff", "255"
Unit II Notes | Page 17 of 18
PHP Tutorial — Unit II: Controlling Program Flow GeeksforGeeks Reference Notes
$from, $to) any two bases 16, 10)
5.7 Number Validation Functions
Function Description
is_finite($n) Returns true if value is a finite float
is_infinite($n) Returns true if value is infinite
is_nan($n) Returns true if value is 'Not a Number'
is_numeric($val) Returns true if value is a number or
numeric string
is_int($val) Returns true if value is an integer
is_float($val) Returns true if value is a float
Example:
<?php
var_dump(is_numeric('123')); // bool(true)
var_dump(is_numeric('12.3')); // bool(true)
var_dump(is_numeric('12abc')); // bool(false)
var_dump(is_nan(sqrt(-1))); // bool(true)
var_dump(is_finite(1/0)); // bool(false)
?>
Unit II Notes | Page 18 of 18