0% found this document useful (0 votes)
16 views92 pages

Web Development Semester Note 7

PHP, or Hypertext Preprocessor, is an open-source server-side scripting language primarily used for web development, allowing the creation of dynamic web pages by embedding PHP code into HTML. It supports various functionalities such as form data processing, database communication, and file manipulation, and features like server-side execution, cross-platform compatibility, and object-oriented programming. PHP has evolved since its introduction in 1994, with multiple versions released, and includes built-in data types, operators, and array structures for efficient data management.
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)
16 views92 pages

Web Development Semester Note 7

PHP, or Hypertext Preprocessor, is an open-source server-side scripting language primarily used for web development, allowing the creation of dynamic web pages by embedding PHP code into HTML. It supports various functionalities such as form data processing, database communication, and file manipulation, and features like server-side execution, cross-platform compatibility, and object-oriented programming. PHP has evolved since its introduction in 1994, with multiple versions released, and includes built-in data types, operators, and array structures for efficient data management.
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 - 5

Php
Hypertext preprocessor
INTRODUCTION

PHP is a popular, open source, server-side


scripting language, executed on the server.
It is used primarily for web development to
create dynamic web pages and applications
by embedding PHP code into HTML.
 PHP was introduced by Rasmus Lerdorf in 1994.
 Initially
called as Personal Home Page  Hypertext Preprocessor by
Zeev Suraski and Andi Gutmans in 1997.
 1994(first version)  1995(PHP tools)  1997(PHP 3)  2000(PHP 4)
 2004(PHP 5)  2015(PHP 7)  2020(PHP 8)  2021(PHP 8.1)  2025(PHP 8.4)
What can do with PHP

 Collect and process form data.


 Generate dynamic content for web pages.
 Communicate with databases, such as MySQL, Oracle, etc.
 PHP can create, open, read, write, delete, and close files on the
server.
 PHP can add, delete, modify data in database.
 Send and receive cookies.
 It can encrypt data and use to control user-access.
 Write command-line scripts.
How PHP Works

A web browser sends a request to a server.


 The server runs the PHP script.
 ThePHP script can interact with a database and perform
other tasks to generate dynamic content.
 Theserver sends the final output, usually HTML, back to
the browser.
Characteristics and Features

1. Server-Side Scripting: PHP code runs on the web server, processing


requests and generating HTML or other content before sending it to the
user's browser.

2. Open Source: PHP is free to use and distribute, fostering a large and
active community that contributes to its development and provides
extensive resources.

3. Embedded in HTML: PHP code can be seamlessly embedded within


HTML, allowing for dynamic content generation directly within web
pages.

4. General-Purpose Language: While primarily known for web


development, PHP can also be used for other scripting tasks and even
command-line applications.
Characteristics and Features
5. Cross-Platform Compatibility: PHP runs on various operating systems,
including Windows, Linux, macOS, and Unix.

6. Database Integration: PHP offers robust support for connecting to a


wide range of databases, such as MySQL, PostgreSQL, Oracle, and
more, facilitating data-driven web applications.

7. Object-Oriented Features: Modern versions of PHP incorporate strong


object-oriented programming (OOP) principles, enabling more
structured and maintainable code.

8. Extensibility: PHP's functionality can be extended through a vast array


of libraries and extensions, catering to diverse development needs.
PHP Installation

Search XAMPP in Browser 


Open XAMPP Installers and Downloads for Apache Friends 
Download (as per your OS) 
run the Installer  follow the process to finish
Basic Syntax of PHP

A PHP script can be written anywhere inside the HTML document. A


PHP script starts with <?php tag and ends with ?> . Inside the tag, code
can be written.

<?php
// PHP code goes here
?>

 The default file extension for PHP files is ".php".


 A PHP file normally contains HTML tags, and some PHP scripting code.
 PHP statements end with a semicolon (;).
Display Output in PHP

In PHP, output is displayed on the browser using echo as follows:

<?php
echo "hello";
Echo "hello";
ECHO "hello";
?>
Comments
A comment is a part of the coding file that the programmer does
not want to execute.

<?php
// This is a single-line comment
# This is also a single-line comment
/*This is a
multiple line
Comment.*/
?>
Variables

Variables are containers that can store information which can be


manipulated or referenced later by the programmer within the
code.

Example :
<?php
$txt = "Hello world!"; # Type String
$z1 = 5; # Type int
?>
Variables Rules

 All variables should be denoted with a Dollar Sign ($).


 Variables are assigned with the = operator, with the variable on
the left-hand side and the expression to be evaluated on the
right.
 Variable names can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
 Variables must start with a letter or the underscore _ character.
 Variables are case sensitive.
 Variable names cannot start with a number.
Constants

In PHP, a constant is an identifier for a simple value that,


once defined, cannot be changed or redefined during
the execution of the script.
A valid constant name starts with a letter or underscore
(no $ sign before the constant name).
Constants
There are two primary ways to define constants in PHP:
1. define() function: This function is used to define global constants.
Example : define("NAME", "My Website");
define("USER", "root");

2. const keyword: This keyword is used to define constants,


typically within a class (class constants) or at the global scope.
Example : const PI = 3.14159; // Global constant
class MyClass {
const MAX_ITEMS = 100; // Class constant
}
const vs. define()
 constcannot be created inside another block scope, like inside a
function or inside an if statement.
 define() can be created inside another block scope.
Data Types

Data type specifies the type of value, a variable requires to do various


operations without causing an error.
PHP supports several built-in data types to store different kinds of values.
PHP is dynamically typed, which determines at runtime based on the
value assigned.
Data Types

By default, PHP provides the following built-in data types:


 String #example : $message = 'Hello World!';
 Integer #example : $age = 30; $count = -10;
 Float #example : $price = 19.99; $pi = 3.14159;
 Boolean #example : $isLogged = true;
 Array #example : $fruits = ["apple", "banana", "orange"];
 NULL #example : $empty = null;
Data Types

In PHP, there are several ways to check the data type of a variable:

1. Using gettype( ) function: returns the type of a variable as a string.


Example :
<?php
$variable = "Hello";
echo gettype($variable); // Output: string
$number = 123;
echo gettype($number); // Output: integer
$array = [1, 2, 3];
echo gettype($array); // Output: array
?>
Data Types
2. Using var_dump() function: displays information, including their type and value.
Example :
<?php
$name = "Alice";
$age = 30;
var_dump($name); //string(5) “Alice”
var_dump($age); //int(30)
?>
3. Using is_* function: used for type checking and return a boolean value (true or false).
Example :
<?php
$value = "PHP";

if (is_string($value)) {
echo "The variable is a string.";
}
?>
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators
Arithmetic Operators
Assignment Operators
The PHP assignment operators are used with numeric values to write a value
to a variable.
Comparison Operators
Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value and
decrement operators are used to decrement a variable's value.
Logical Operators
String Operators

PHP has two operators that are specially designed for strings.
Array Operators
Conditional Assignment Operators
Conditional Statements

Conditional statements are used to perform different actions based on


different conditions.
In PHP, the following conditional statements are:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and
another code if that condition is false
 if...elseif...else statement - executes different codes for more than two
conditions.
 switch statement - selects one of many blocks of code to be executed
The if Statements

The if statement executes some code if one condition is true.


Syntax
if (condition) {
// code to be executed if condition is true;
}
Example :
$t = 14;
if ($t < 20) {
echo "Have a good day!";
}
The if….else Statements
The if...else statement executes some code if a condition is true and
another code if that condition is false.
Syntax : if (condition) {
// code to be executed if condition is true;
} else {
// code to be executed if condition is false;
}
Example : $t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
The if….elseif….else Statements

The if...elseif...else statement executes different codes for more than two
conditions.
Syntax : if (condition) {
//code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is
true;
} else {
// code to be executed if all conditions are false;
}
The if….elseif….else Statements
Example :
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
Short Hand If...Else
if...else statements can also be written in one line, but the syntax is a bit
different.
$a = 13;
$b = $a < 10 ? "Hello" : "Good Bye";
echo $b;
This technique is known as Ternary Operators, or Conditional Expressions.

PHP Nested if Statement


You can have if statements inside if statements, this is
called nested if statements.
$a = 13;
if ($a > 10) { echo "Above 10";
if ($a > 20) { echo " and also above 20"; }
else { echo " but not above 20"; } }
Switch Statements
The PHP switch statement is used to perform different actions based on
different conditions.
Syntax Example : $favcolor = "red";
switch (expression) { switch ($favcolor) {
case label1: case "red":
//code block echo "Your favorite color is red!";
break; break;
case label2: case “blue”:
//code block; echo "Your favorite color is blue!";
break; break;
default: default:
//code block echo “neither red nor blue!";
} }
The PHP break Keyword

When PHP reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code, and no more cases are tested.
The last block does not need a break, the block breaks (ends) there
anyway.
Warning: If you omit the break statement in a case that is not the last, and
that case gets a match, the next case will also be executed even if the
evaluation does not match the case.
Common Code Blocks
If you want multiple cases to use the same code block, you can specify
the cases like this: $d = 3;
switch ($d) {
case 1:
case 2:
case 3:
echo "The weeks feels so long!";
break;
case 6:
case 0:
echo "Weekends are the best!";
break;
default:
echo "Something went wrong"; }
Array
PHP arrays are powerful and flexible data structures used to store multiple
values in a single variable.
They are essentially ordered maps, allowing for both integer and string
keys to access their associated values.

 PHP offers many built-in array functions for sorting, merging, searching,
and more.
 PHP Arrays can store values of different types (e.g., strings, integers,
objects, or even other arrays) in the same array.
 They are dynamically sized.
 They allow you to store multiple values in a single variable, making it
easier to manage related data
There are three primary types of arrays in PHP:

1. Indexed Arrays: These arrays use numeric keys, starting from 0 by


default, to store and access elements. Values are typically stored and
accessed in a linear fashion.
Example : $fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Outputs: Apple
2. Associative Arrays: These arrays use named keys (strings) to store and
access elements, providing a more descriptive way to organize data.
Example : $school = [
"name" => “gietu",
"age" => 30,
"city" => “gunupur" ];
echo $school["name"]; // Outputs: gietu
3. Multidimensional Arrays: These arrays contain one or more arrays as
their elements, allowing for the representation of complex, hierarchical
data structures, such as matrices or tables.
Example : <?php
$students = array(
“ASA" => array("age" => 25, "grade" => "A"),
“DSA" => array("age" => 24, "grade" => "B")
);
echo $students[“ASA"]["age"];
?>
Create Arrays

In PHP, arrays can be created using two main methods:

1. Array can create by using array() function.


$fruits = array("apple", "banana", "cherry");
2. By using short array syntax( [ ] )
$fruits = ["apple", "banana", "cherry"];

Creating indexed arrays the keys;


$fruits = [0 => "apple", 1 => "banana", 2 => "cherry"];
Access Arrays Items

To access an array item by its index number for indexed arrays.


$fruits = array("apple", "banana", "cherry");
Echo $fruits[2];
To access an array item using its key name for associative arrays.
$fruits = [“fn1” => "apple", “fn2” => "banana", “fn3” => "cherry"];
Modify/Update Arrays Items

To modify an array item by its index number for indexed arrays.


$fruits = array("apple", "banana", "cherry");
$fruits[2]= “grapes";
To modify an array item using its key name for associative arrays.
$fruits = [“fn1” => "apple", “fn2” => "banana", “fn3” => "cherry"];
$fruits = [“fn1”] => “KIWI“ ;
Adding Arrays Items

To add an array item in the array, [ ] syntax is used.


$fruits = array("apple", "banana", "cherry");
$fruits[ ]= “grapes";
To add an array item using its key name for associative arrays.
$fruits = [“fn1” => "apple", “fn2” => "banana", “fn3” => "cherry"];
$fruits[“fn1”] => “KIWI“ ;
Adding Arrays Items

To add multiple array item, array_push( ) function is used.


It will add items in end of the array.
$fruits = array("apple", "banana", "cherry");
array_push($fruits, “grapes“, “Lemon”) ;
To add multiple array item, array_unshift( ) function is used.
It will add items in first of the array.
$fruits = array("apple", "banana", "cherry");
array_unshift($fruits, “Lemon”) ;
Removing Arrays Items
To remove the last array item, array_pop( ) function is used.
$fruits = array("apple", "banana", "cherry");
array_pop($fruits) ;
To remove the first array item, array_shift( ) function is used.
$fruits = array("apple", "banana", "cherry");
array_shift($fruits) ;
To remove a specific array item, unset( ) function is used.
$fruits = array("apple", "banana", "cherry");
unset($fruits[2]) ;
To remove a multiple array item, array_splice( ) function is used.
$fruits = array("apple", "banana", "cherry");
array_splice($fruits, 1,2 ) ;
Arrays Functions
PHP provides a wide range of built-in functions to work with arrays. Here
are some common array functions; -
Array Merge: The array_merge() function combines two or more arrays
into one.
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: [1, 2, 3, 4, 5, 6]
Arrays Functions
Array Search: The in_array( ) function checks if a specific value exists in an
array.
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array!";
}
Array Sort: The sort() function sorts an indexed array in ascending order..
The rsort() function sorts an indexed array in descending order..
$numbers = [3, 1, 4, 1, 5];
$res= sort($numbers);
echo($res); // Outputs: [1, 1, 3, 4, 5]
Arrays Functions
Array Search: The in_array( ) function checks if a specific value exists in an
array.
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array!";
}
Array Sort: The sort() function sorts an indexed array in ascending order..
The rsort() function sorts an indexed array in descending order..
$numbers = [3, 1, 4, 1, 5];
$res= sort($numbers);
echo($res); // Outputs: [1, 1, 3, 4, 5]
PHP Associative Arrays

An associative array in PHP is a special array where each item has a


name or label instead of just a number. Usually, arrays use numbers to find
things.
 For example, the first item is at position 0, the second is 1, and so on.
 But in an associative array, we use words or names to find things.
 These names are called keys.
 For example, instead of saying "give me the item at position 0," we say
"give me the item with the name ‘name’" or "the item with the name
‘age’."
PHP Associative Arrays

Example : Using short syntax (PHP 5.4+)


<?php
$array = array( $person = [
"name" => "Anjali",
"key1" => "value1", "age" => 23,
"key2" => "value2", "city" => "New York"
];
"key3" => "value3"
); echo $person["name"] . "\n";
echo $person["age"] . "\n";
echo $person["city"] . "\n";
?>
Iterating Through an Associative Arrays

The easiest way to loop through an associative array is by using


the foreach loop. It lets us access both the key and the value in each
iteration.
1. Using foreach loop :
<?php
$fruits = [
"apple" => "red",
"banana" => "yellow“ ];
foreach ($fruits as $fruit => $color) {
echo "The color of $fruit is $color.\n";
}
?>
Iterating Through an Associative Arrays
2. Using loop with keys arrays : If you want to use a for loop instead
of foreach, you first need to get all the keys using array_keys(). Then you
can loop through these keys and access their values.
<?php
$fruits = [
"apple" => "red",
"banana" => "yellow" ];
$keys = array_keys($fruits);
for ($i = 0; $i < count($keys); $i++) {
$fruit = $keys[$i];
echo "The color of $fruit is " . $fruits[$fruit] . ".\n";
} ?>
Accessing and Modifying Values Using Keys
1. Checking if a Key Exists: Before working with a key, it’s good to check if
it exists to avoid errors. You can use array_key_exists() or isset() for this.
<?php
$data = [ "x" => 100, "y" => 200 ];
if (array_key_exists("x", $data)) {
echo "Key 'x' is present in the array.\n"; }
if (isset($data["z"])) {
echo "Key 'z' is set.\n"; }
else {
echo "Key 'z' does not exist.\n"; }
?>
Accessing and Modifying Values Using Keys
2. Removing Elements from an Associative Array : To remove a key-value
pair, use the unset() function with the key.
<?php
$items = [
"first" => "one",
"second" => "two",
"third" => "three“ ];
unset($items["second"]);
echo($items);
?>
Useful Built-in Functions for Associative Arrays

PHP provides many built-in functions to work with arrays, including


associative arrays. Some useful ones are:

 array_keys($array): Returns all keys of the array.


 array_values($array): Returns all values of the array.
 array_key_exists("key", $array): Checks if a key exists.
 count($array): Returns the number of elements.
 unset($array["key"]): Removes a key-value pair.
When to Use Associative Arrays?

Associative arrays are useful when:

 You want to associate meaningful keys with values (e.g., user info,
product details).
 You want to access elements by name instead of by position.
 You want to represent structured data without creating a class or
object.
Multidimensional arrays in PHP

 Multi-dimensional arrays in PHP are arrays that store other arrays as their
elements.
 Eachdimension adds complexity, requiring multiple indices to access
elements.
 Common forms include two-dimensional arrays (like tables) and three-
dimensional arrays, useful for organizing complex, structured data.
 Dimensionsof multidimensional array indicates the number of indices
needed to select an element.
Two Dimensional Array
 It is the simplest form of a multidimensional array.
 It can be created using nested array.
 These type of arrays can be used to store any type of elements, but the
index is always a number.
 By default, the index starts with zero.
 For a two dimensional array two indices to select an element.
Syntax:
array (
array (elements...),
array (elements...),
... )
Two Dimensional Array
Example:
 Inthis example ,it creates a two-dimensional array containing names
and locations.
 The print_r() function is used to display the structure and contents of the
array, showing the nested arrays and their values.
<?php output
$myarray = array( Array
array("Ankit", "Ram", "Shyam"), (
array("Unnao", "Trichy", "Kanpur") ); [0]=> Array
// Display the array information (
print_r($myarray); [0] =>Ankit
?> [1]=>Ram
[2]=>Shyam
) …….
Accessing Multidimensional Array Elements

There are mainly two ways to access multidimensional array elements in


PHP.
 Elementscan be accessed using dimensions as array_name['first
dimension']['second dimension'].
 Elements can be accessed using for loop.
 Elements can be accessed using for each loop.
Accessing Multidimensional Array Elements
<?php

$marks = array( ),
"Ankit" => array( );
"C" => 95,
"DCO" => 85,
"FOL" => 74,
Example : ),
"Ram" => array( echo $marks['Ankit']['C'] . "\n";
"C" => 78, // Accessing array elements using for
"DCO" => 98, each loop
"FOL" => 46, foreach($marks as $mark) {
), echo $mark['C']. " ".$mark['DCO']."
Output
"Anoop" => array( ".$mark['FOL']."\n";
95
"C" => 88, } 95 85 74
"DCO" => 46, ?> 78 98 46
"FOL" => 99, 88 46 99
Sort an Array in Ascending Order According to Array Values -
asort() Function

The asort() function sorts an array by values in ascending order while


maintaining the key-value association.
<?php
$arr = array( Output
"Ayush"=>"23", Array
"Shankar"=>"47", (
"Kailash"=>"41“ ); [Ayush] => 23
asort($arr); [Kailash] => 41
print_r($arr) [Shankar] => 47 )
Sort an Array in Descending Order According to Array Values
- arsort() Function

The arsort() function sorts an array by values in descending order while


maintaining the key-value association.
<?php
$arr = array( Output
"Ayush"=>"23", Array
"Shankar"=>"47", (
"Kailash"=>"41“ ); [Shankar] => 47
arsort($arr); [Kailash] => 41
print_r($arr) [Ayush]=>23 )
Sort an Array in Ascending Order According to Array keys -
ksort() Function

The ksort() function sorts an array by values in ascending order while


maintaining the key-value pairs.
<?php
$arr = array( Output
"Ayush"=>"23", Array
"Shankar"=>"47", (
"Kailash"=>"41“ ); [Ayush] => 23
ksort($arr); [Kailash] => 41
print_r($arr) [Shankar] => 47 )
Sort an Array in Descending Order According to Array Keys -
krsort() Function

The krsort() function sorts an array by values in descending order while


maintaining the key-value pairs.
<?php
$arr = array( Output
"Ayush"=>"23", Array
"Shankar"=>"47", (
"Kailash"=>"41“ ); [Shankar] => 47
krsort($arr); [Kailash] => 41
print_r($arr) [Ayush]=>23 )
PHP Functions

PHP functions are named blocks of code designed to perform specific


tasks, used repeatedly in a program.
They can accept inputs (parameters), execute a set of instructions, and
optionally return a value.
Functions can accept input values, known as parameters or arguments.
Parameters are variables defined in the function declaration that accept
values.
Arguments are the actual values passed to the function when it is called.
Create a Function

A user-defined function declaration starts with the keyword function,


followed by the name of the function:
Example :
function msg() {
echo “Hello” ;
}
msg();
A function name must start with a letter or an underscore.
Function names are NOT case-sensitive.
To call the function, just write its name followed by parentheses ():
PHP Functions
These values can be passed to the function in two ways:
1. Passing by Value
When you pass a value by reference, the function works with a copy of
the argument. This means the original value remains unchanged.
<?php
function add($x, $y) {
$x = $x + $y;
return $x;
}
echo add(2, 3); // Outputs: 5
?>
PHP Functions
2. Passing by Reference
By passing an argument by reference, any changes made inside the
function will affect the original variable outside the function..
<?php
function addByRef(&$x, $y) {
$x = $x + $y;
}
$a = 5;
addByRef($a, 3);
echo $a; // Outputs: 8
?>
Returning Values in PHP Functions
Functions in PHP can return a value using the return statement. The return
value can be any data type such as a string, integer, array, or object. If
no return statement is provided, the function returns null by default.
<?php
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(4, 5); // $result will be 20
echo $result; // Output: 20
?>
Recursion in PHP
Recursion is a process in which a function calls itself. It is often used in
situations where a task can be broken down into smaller, similar tasks.
<?php
function factorial($n) {
if ($n == 0) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5);
?>
Common PHP Functions
1. String Functions
strlen(): Returns the length of a string.
strtoupper(): Converts a string to uppercase.
strtolower(): Converts a string to lowercase.
substr(): Returns a part of a string.
2. Array Functions
array_push(): Adds elements to the end of an array.
array_pop(): Removes the last element of an array.
array_merge(): Merges two or more arrays.
3. Date and Time Functions
date(): Returns the current date or time.
strtotime(): Converts a string into a Unix timestamp.
time(): Returns the current Unix timestamp.
PHP Loops

In PHP, Loops are used to repeat a block of code multiple times based on
a given condition. PHP provides several types of loops to handle different
scenarios, including while loops, for loops, do...while loops, and foreach
loops.
Types of Loops in PHP
 for loop
 while loop
 do-while loop
 foreach loop
1. PHP for Loop
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 of the loop variable.
Condition: Checks if the loop should continue.
Increment/Decrement: Changes the loop variable after each iteration.
Syntax for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed }
Example : <?php
for ($num = 1; $num <= 5; $num += 1) {
echo $num . "\n";
}
?>
2. PHP while Loop
The while loop is also an entry control loop like for loops. It first checks the
condition at the start of the loop, and if it's true then it enters into the loop
and executes the block of statements and goes on executing it as long as
the condition holds true.
Syntax : while ( condition ) {
// Code is executed
}
Example : <?php
$num = 1;
while ($num <= 5) {
echo $num . "\n";
$num++;
}
?>
3. PHP do-while Loop
The do-while loop is an exit control loop, which means, it first enters the
loop, executes the statements, and then checks the condition. Therefore,
a statement is executed at least once using the do...while loop. After
executing once, the program is executed as long as the condition holds
true.
Syntax : do {
// Code is executed
} while ( condition );
Example : <?php
$num = 1;
do {
echo $num . "\n";
$num++;
} while ($num <= 5);
?>
4. PHP foreach Loop
This foreach loop is used to iterate over arrays. For every counter of loop,
an array element is assigned, and the next counter is shifted to the next
element. It simplifies working with arrays and objects by automatically
iterating through each element.
Syntax:
foreach ( $array as $value ) {
// Code to be executed
}
or,
foreach ($array as $key => $value) {
// Code to be executed
}
$array: The array to iterate over.
$value: The current value of the array element during each iteration.
Example : <?php
// foreach loop over an array
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $val) {
echo $val . " "; }
echo "\n";
// foreach loop over an array with keys
$ages = array(
"Anjali" => 25,
"Kriti" => 30,
"Ayushi" => 22 );
foreach ($ages as $name => $age) {
echo $name . " => " . $age . "\n";
}
?>
Create a two-dimensional associative array to store students' marks
for various subjects. The print_r() function displays the array, showing
each student's name as a key with subject-marks pairs.
PHP Regular Expressions
A regular expression is a sequence of characters that forms a search
pattern. When you search for data in a text, you can use this search
pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated
pattern.
Regular expressions can be used to perform all types of text search and
text replace operations.
Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern
and optional modifiers.
$exp = "/giet/i";
In the example above, / is the delimiter, giet is the pattern that is being
searched for, and i is a modifier that makes the search case-insensitive.
Regular Expression Functions
PHP provides a variety of functions that allow you to use regular
expressions.
The most common functions are:

Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the
string, which may also be 0

preg_replace() Returns a new string where matched patterns have been


replaced with another string
Using preg_match() : The preg_match() function will tell you whether a
string contains matches of a pattern.
$str = "Visit GIET";
$pattern = "/GIET/i";
echo preg_match($pattern, $str);
Using preg_match_all() : The preg_match_all() function will tell you how
many matches were found for a pattern in a string.
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
Using preg_replace() : The preg_replace() function will replace all of the
matches of the pattern in a string with another string.
$str = "Visit Microsoft!";
$pattern = "/ Microsoft /i";
echo preg_replace($pattern, "GIET", $str);
Regular Expression Patterns
PHP Include Files
The include (or require) statement takes all the text/code/markup that
exists in the specified file and copies it into the file that uses the include
statement.
Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website.

PHP include and require Statements


It is possible to insert the content of one PHP file into another PHP file
(before the server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
 require will produce a fatal error (E_COMPILE_ERROR) and stop the
script.
 includewill only produce a warning (E_WARNING) and the script will
continue.
So, if you want the execution to go on and show users the output, even if
the include file is missing, use the include statement. Otherwise, in case of
FrameWork, CMS, or a complex PHP application coding, always use the
require statement to include a key file to the flow of execution. This will
help avoid compromising your application's security and integrity, just in-
case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a
standard header, footer, or menu file for all your web pages. Then, when
the header needs to be updated, you can only update the header
include file.
Syntax :
include 'filename';

or

require 'filename';
[Link]
<?php
echo "<p>Copyright &copy; 2025-" . date("Y") . " GIET
University</p>";
?>
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include '[Link]';?>

</body>
</html>
[Link]
<?php
echo '<a href="/[Link]">Home</a> -
<a href="/html/[Link]">HTML </a> -
<a href="/css/[Link]">CSS</a> -
<a href="/js/[Link]">JavaScript </a> -
<a href="[Link]">PHP</a>';
?>
All pages in the Web site should use this menu file.
<html>
<body>
<div class="menu">
<?php include '[Link]';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>
[Link]
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "[Link]" file, the variables can be used in the calling
file:
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php include '[Link]';
echo "I have a $color $car.";
?>

</body>
</html>
PHP include vs. require
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when
a file is included with the include statement and PHP cannot find it, the
script will continue to execute:

Use require when the file is required by the application.


Use include when the file is not required and application should continue
when file is not found.

You might also like