0% found this document useful (0 votes)
21 views95 pages

Module 2 WAD

The document provides a comprehensive overview of PHP, detailing its origins, uses, and key syntactic characteristics. It covers various aspects of PHP programming, including data types, operators, and control statements, essential for web application development. The content is structured into modules, with practical examples illustrating PHP functionalities.

Uploaded by

tasleembanu907
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)
21 views95 pages

Module 2 WAD

The document provides a comprehensive overview of PHP, detailing its origins, uses, and key syntactic characteristics. It covers various aspects of PHP programming, including data types, operators, and control statements, essential for web application development. The content is structured into modules, with practical examples illustrating PHP functionalities.

Uploaded by

tasleembanu907
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/ 95

BAPUJI EDUCATIONAL ASSOCIATION(REGD.

)
BAPUJI INSTITUTE OF ENGINEERING AND TECHNOLOGY, DAVANGERE-577004
AN AUTONOMOUS INSTITUTE AFFILIATED TO VTU, BELAGAVI, KARNATAKA, INDIA

Department of Master of Computer Applications

WEB APPLICATION DEVELOPMENT

MODULE : 2

Presented by
VINUTHA D K
Asst. Professor Dept. of MCA
TABLE OF CONTENTS
Sl. No Topic
1 Origins and uses of PHP
2 Overview of PHP
3 General Syntactic characteristics
4 Primitives, Operations and Expressions
5 Output
6 Control Statements
7 Arrays, Functions, Pattern Matching
8 Form handling
9 Files
10 Cookies, Sessions
11 Using databases, Handling XML
ORIGINS AND USES OF PHP
• PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus lerdorf released the first version of PHP way back in 1994. Initially,
PHP was supposed to be an abbreviation for "personal home page", but it now stands for the
recursive initialism "PHP: hypertext preprocessor".
• PHP stands for hypertext preprocessor. It is an open-source, widely used language for web
development. Developers can create dynamic and interactive websites by embedding PHP code
into HTML. PHP can handle data processing, session management, form handling, and database
integration. The latest version of PHP is PHP 8.4, released in 2024.
• Php is a server-side scripting language that generates dynamic content on the server and interacts
with databases, forms, and sessions.
• Php supports easy interaction with databases like mysql, enabling efficient data handling.
• Php runs on multiple operating systems and works with popular web servers like apache
and nginx.
OVERVIEW OF PHP
• PHP is a widely used, open-source, server-side scripting language primarily designed for web
development. It's embedded within HTML and generates dynamic content, making it essential for
building data-driven websites and applications. PHP allows developers to manage databases,
track user sessions, and handle various web-related tasks.
• HOW PHP WORKS?
• The server determines that a document includes PHP script by the file name extension. If it is
.php, .php3, or .phtml, it has embedded PHP.
• The PHP processor has two modec of operations, copy mode, interpret mode.
• It takes a PHP document file as input and produces an XHTML code in the input file, it simply
copies it to the output file.When it encounters PHP script in the input file, it interprets it and sends
any output of the script to the output file. This implies that the output from a PHP script must be
XHTML or embedded client-side script.
• This new file is sent to the requesting browser. The client never sees the PHP script. If he clicks
View source while the browser is displaying the document, only the XHTML will be shown,
because that is all that ever arrives at the client.
• PHP has an extensive library of functions, making it a flexible and powerful tool for server-side
software development
GENERAL SYNTACTIC CHARACTERISTICS
• A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
• A php script can be placed anywhere in the document.
• A php script starts with <?php and ends with ?>:
• Syntax
<?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.
• Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page
• Example
<!Doctype html>
<html>
<body>
<h1>my first PHP page</h1>
<?php
echo "hello world!";
?>
</body>
</html>
• PHP statements end with a semicolon (;).
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are not case-sensitive.
• A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
• / This is a single-line comment
• # This is also a single-line comment
• /* This is amulti-line comment */
PRIMITIVES, OPERATIONS AND EXPRESSIONS
• Variables can store data of different types, and different data types can do different things.
• PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
Null
Resource
• PHP STRING:A string is a sequence of characters, like "hello world!“. A string can be any text inside quotes. You
can use single or double quotes.
• Example: $x = "hello world!";
$y = 'hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
• PHP Integer:An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
• Rules for integers:
o An integer must have at least one digit
o An integer must not have a decimal point
o An integer can be either positive or negative
o Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary
(base 2) notation
• In the following example $x is an integer. The PHP var_dump() function returns the data type and
value
• Example: $x = 5985;
var_dump($x);
• PHP float:A float (floating point number) is a number with a decimal point or a number in
exponential form.
• In the following example $x is a float. The PHP var_dump() function returns the data type and value:
• Example : $x = 10.365;
var_dump($x);
• PHP Boolean: A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.
• Example:$x = true;
var_dump($x);
OPERATIONS
• Operators are used to perform operations on variables and values.
• In PHP, operators are special symbols used to perform operations on variables and values. Operators help you
perform a variety of tasks, such as mathematical calculations, string manipulations, logical comparisons, and more.
Understanding operators is essential for writing effective and efficient PHP code. PHP operators are categorized
into several types:
• PHP divides the operators in the following groups:
o Arithmetic operators
o Assignment operators
o Comparison operators
o Increment/decrement operators
o Logical operators
o String operators
o Array operators
o Conditional assignment operators
• 1. ARITHMETIC OPERATORS
• Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction,
multiplication, division, and modulus.

Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

- Subtraction $x - $y Differences in the Operands

* Multiplication $x * $y Product of the operands

/ Division $x / $y The quotient of the operands

** Exponentiation $x ** $y $x raised to the power $y

The remainder of the


% Modulus $x % $y
operands
• Example:
<?php
// define two numbers
$x = 10;
$y = 3;

// addition
echo "addition: " . ($x + $y) . "\n";

// subtraction
echo "subtraction: " . ($x - $y) . "\n";

// multiplication
echo "multiplication: " . ($x * $y) . "\n";

// division
echo "division: " . ($x / $y) . "\n";

// exponentiation
echo "exponentiation: " . ($x ** $y) . "\n";

// modulus
echo "modulus: " . ($x % $y) . "\n";
?>
• 2. Logical operators
• Logical operators are used to operate with conditional statements. These operators evaluate
conditions and return a boolean result (true or false).

Operator Name Syntax Operation

True if both the operands are


and Logical AND $x and $y
true else false

True if either of the operands


or Logical OR $x or $y
is true otherwise, it is false

True if either of the operands


xor Logical XOR $x xor $y
is true and false if both are true

True if both the operands are


&& Logical AND $x && $y
true else false

True if either of the operands


|| Logical OR $x || $y
is true otherwise, it is false

! Logical NOT !$x True if $x is false


• EXAMPLE:
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and success \n";

if ($x == 50 or $y == 20)
echo "or success \n";

if ($x == 50 xor $y == 20)


echo "xor success \n";

if ($x == 50 && $y == 30)


echo "&& success \n";

if ($x == 50 || $y == 20)
echo "|| success \n";

if (!$z)
echo "! success \n";
?>
• 3. Comparison operators
• Comparison operators are used to compare two values and return a boolean result (true or false).

Operator Name Syntax Operation

== Equal To $x == $y Returns True if both the operands are equal

!= Not Equal To $x != $y Returns True if both the operands are not equal

<> Not Equal To $x <> $y Returns True if both the operands are unequal

Returns True if both the operands are equal and are of


=== Identical $x === $y
the same type

Returns True if both the operands are unequal and are of


!== Not Identical $x == $y
different types

< Less Than $x < $y Returns True if $x is less than $y

> Greater Than $x > $y Returns True if $x is greater than $y

<= Less Than or Equal To $x <= $y Returns True if $x is less than or equal to $y

>= Greater Than or Equal To $x >= $y Returns True if $x is greater than or equal to $y
• EXAMPLE:
<?php
$a = 80;
$b = 50;
$c = "80";
// here var_dump function has been used to
// display structured information.
var_dump($a == $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a <> $b) + "\n";
var_dump($a === $c) + "\n";
var_dump($a !== $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
• 4. Conditional or ternary operators
• These operators are used to compare two values and take either of the results simultaneously,
depending on whether the outcome is TRUE or FALSE. These are also used as a shorthand
notation for the if...Else statement that we will read in the article on decision making.
• Syntax: $var = (condition)? value1 : value2;

Operator Name Operation


If the condition is true? then $x
: or else $y. This means that if
the condition is true, then the
?: Ternary
left result of the colon is
accepted otherwise, the result is
on the right.
• EXAMPLE:
<?php
$x = -12;
echo ($x > 0) ? 'the number is positive' : 'the number is negative';
?>
• 5. Assignment operators
• Assignment operators are used to assign values to variables. These operators allow you to assign
a value and perform operations in a single step.

Operator Name Syntax Operation

Operand on the left obtains the


= Assign $x = $y
value of the operand on the right

Simple Addition same as $x =


+= Add then Assign $x += $y
$x + $y

Simple subtraction same as $x =


-= Subtract then Assign $x -= $y
$x - $y

Simple product same as $x = $x


*= Multiply then Assign $x *= $y
* $y

Simple division same as $x = $x


/= Divide, then assign (quotient) $x /= $y
/ $y

Simple division same as $x = $x


%= Divide, then assign (remainder) $x %= $y
% $y
• EXAMPLE: // multiply then assign operator
<?php $y = 30;
// simple assign operator $y *= 20;
$y = 75; echo $y, "\n";
echo $y, "\n";
// divide then assign(quotient) operator
// add then assign operator $y = 100;
$y = 100; $y /= 5;
$y += 200; echo $y, "\n";
echo $y, "\n";
// divide then assign(remainder) operator
// subtract then assign operator $y = 50;
$y = 70; $y %= 5;
$y -= 10; echo $y;
echo $y, "\n"; ?>
• 6. Array operators
• These operators are used in the case of arrays. Here are the array operators, along with their
syntax and operations, that PHP provides for the array operation.

Operator Name Syntax Operation

+ Union $x + $y Union of both, i.e., $x and $y

Returns true if both have the


== Equality $x == $y
same key-value pair

!= Inequality $x != $y Returns True if both are unequal

Returns True if both have the


=== Identity $x === $y same key-value pair in the same
order and of the same type

Returns True if both are not


!== Non-Identity $x !== $y
identical to each other

<> Inequality $x <> $y Returns True if both are unequal


• EXAMPLE:
<?php
$x = array("k" => "car", "l" => "bike");
$y = array("a" => "train", "b" => "plane");

var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
• 7. Increment/decrement operators
• These are called the unary operators as they work on single operands. These are used to
increment or decrement values.

Operator Name Syntax Operation

First, increment $x by one,


++ Pre-Increment ++$x
then return $x

First, decrement $x by one,


-- Pre-Decrement --$x
then return $x

First returns $x, then


++ Post-Increment $x++
increment it by one

First, return $x, then


-- Post-Decrement $x--
decrement it by one
• EXAMPLE

<?php

$x = 2;

echo ++$x, " first increments then prints \n";

echo $x, "\n";

$x = 2;

echo $x++, " first prints then increments \n";

echo $x, "\n";

$x = 2;

echo --$x, " first decrements then prints \n";

echo $x, "\n";

$x = 2;

echo $x--, " first prints then decrements \n";

echo $x;

?>
• 8. String operators
• This operator is used for the concatenation of 2 or more strings using the concatenation operator
('.'). we can also use the concatenating assignment operator ('.=') to append the argument on the
right side to the argument on the left side.
• Example:
<?php
Operator Name Syntax Operation
$x = "geeks";
$y = "for";
Concatenated $x and
$z = "geeks!!!"; . Concatenation $x.$y
$y
echo $x . $y . $z, "\n";
$x .= $y . $z;
First, it concatenates
echo $x; .=
Concatenation and
$x.=$y then assigns, the
assignment
?> same as $x = $x.$y
• PHP | bitwise operators
• The bitwise operators is used to perform bit-level operations on the operands. The operators are
first converted to bit-level and then calculation is performed on the operands. The mathematical
operations such as addition , subtraction , multiplication etc. Can be performed at bit-level for
faster processing. In PHP, the operators that works at bit level are:
• PHP | ternary operator
• If-else and switch cases are used to evaluate conditions and decide the flow of a program. The
ternary operator is a shortcut operator used for shortening the conditional statements.
• Ternary operator: the ternary operator (?:) is a conditional operator used to perform a simple
comparison or check on a condition having simple statements. It decreases the length of the code
performing conditional operations. The order of operation of this operator is from left to right. It
is called a ternary operator because it takes three operands- a condition, a result statement for
true, and a result statement for false. The syntax For the ternary operator is as follows.
• Syntax: (Condition) ? (statement1) : (statement2);
EXPRESSIONS
• Almost everything in a PHP script is an expression. Anything that has a value is an expression. In
a typical assignment statement ($x=100), a literal value, a function or operands processed by
operators is an expression, anything that appears to the right of assignment operator (=)
• SYNTAX
o $x=100; //100 is an expression
o $a=$b+$c; //b+$c is an expression
o $c=add($a,$b); //add($a,$b) is an expresson
o $val=sqrt(100); //sqrt(100) is an expression
o $var=$x!=$y; //$x!=$y is an expression
• EXPRESSION WITH ++ AND -- OPERATORS
• These operators are called increment and decrement operators respectively. They are unary operators,
needing just one operand and can be used in prefix or postfix manner, although with different effect on
value of expression
• Both prefix and postfix ++ operators increment value of operand by 1 (whereas -- operator decrements
by 1). However, when used in assignment expression, prefix makes incremnt/decrement first and then
followed by assignment. In case of postfix, assignment is done before increment/decrement
• EXAMPLE:
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
• Expression with ternary conditional operator
• Ternary operator has three operands. First one is a logical expression. If it is TRU, second
operand expression is evaluated otherwise third one is evaluated
• EXAMPLE:
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
OUTPUT
• echo and print are more or less the same. They are both used to output data to the screen.
• The differences are small: echo has no return value while print has a return value of 1 so it can
be used in expressions.
• echo can take multiple parameters (although such usage is rare) while print can take one
argument.
• echo is marginally faster than print.
CONTROL STATEMENTS
• PHP control statements, also known as control structures, are used to control the flow of
execution in a program by determining which code blocks will be executed based on conditions
or by repeating blocks of code. These statements are essential for making decisions, iterating
through code, and jumping to specific parts of the program.
• Types of control statements in PHP:
• Conditional statements:
• if statement: executes a block of code if a condition is true.
• elseif statement: checks another condition if the previous if or elseif condition is false.
• else statement: executes a block of code if none of the previous if or elseif conditions are true.
• Switch statement: selects one block of code to execute from multiple options based on the value
of an expression.
• Loop statements:
• for loop: repeats a block of code a specified number of times, using an initialization, condition,
and increment/decrement.
• while loop: repeats a block of code as long as a condition is true.
• do-while loop: similar to while, but executes the block of code at least once before checking the
condition.
• foreach loop: iterates through an array, executing a block of code for each element.
• Jump statements:
• Break statement: exits from a loop or switch statement.
• Continue statement: skips the current iteration of a loop and proceeds to the next.
• goto statement: transfers control to a labeled location in the code.
<?php default:
echo "<h2>demonstrating php control statements</h2>"; echo "just another day.<br>";
// 1. if-else statement }
echo "<h3>1. if-else statement</h3>"; echo "<br>";
$temperature = 28;
if ($temperature > 25) { // 4. for loop
echo "it's a hot day! ($temperature°c)<br>"; echo "<h3>4. for loop (counting to 5)</h3>";
} else { for ($i = 1; $i <= 5; $i++) {
echo "the weather is mild. ($temperature°c)<br>"; echo "count: $i<br>";
} }
echo "<br>"; echo "<br>";

// 2. if-elseif-else statement // 5. while loop with 'break'


echo "<h3>2. if-elseif-else statement</h3>"; echo "<h3>5. while loop with 'break' (counting to 3, then stopping)</h3>";
$grade = 85; $count = 1;
if ($grade >= 90) { while ($count <= 10) {
echo "excellent! your grade is a. ($grade)<br>"; echo "current count: $count<br>";
} elseif ($grade >= 80) { if ($count == 3) {
echo "very good! your grade is b. ($grade)<br>"; echo "reached 3, breaking the loop.<br>";
} elseif ($grade >= 70) { break; // exits the while loop
echo "good! your grade is c. ($grade)<br>"; }
} else { $count++;
echo "you can do better. your grade is below c. ($grade)<br>"; }
} echo "<br>";
echo "<br>";
// 6. do-while loop with 'continue'
// 3. switch statement echo "<h3>6. do-while loop with 'continue' (printing odd numbers up to 7)</h3>";
echo "<h3>3. switch statement</h3>"; $num = 0;
$day = "wednesday"; do {
switch ($day) { $num++;
case "monday": if ($num % 2 == 0) { // if number is even
echo "it's the start of the week.<br>"; echo "skipping even number: $num<br>";
break; continue; // skips the rest of the current iteration
case "wednesday": }
echo "it's hump day!<br>"; echo "odd number: $num<br>";
break; } while ($num < 7);
case "friday": echo "<br>";
echo "thank god it's friday!<br>";
break; ?>
ARRAYS, FUNCTIONS, PATTERN MATCHING
• Arrays are one of the most important data structures in PHP. They allow you to store multiple
values in a single variable. PHP arrays can hold values of different types, such as strings,
numbers, or even other arrays. Understanding how to use arrays in PHP is important for working
with data efficiently.
• 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.
• Types of arrays in PHP
• There are three main types of arrays in PHP:
1. Indexed arrays
• Indexed arrays use numeric indexes starting from 0. These arrays are ideal when you need to store a
list of items where the order matters.
• Example
<?php
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
?>
You can also explicitly define numeric keys in an indexed array:
<?php
$fruits = array(0 => "apple", 1 => "banana", 2 => "cherry");
?>
2. Associative arrays
• Associative arrays use named keys, which are useful when you want to store data with
meaningful identifiers instead of numeric indexes.
• Example:
<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York");
echo $person["name"];
?>
3. Multidimensional arrays
• Multidimensional arrays are arrays that contain other arrays as elements. These are used to
represent more complex data structures, such as matrices or tables.
• Example:
<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"GFG" => array("age" => 22, "grade" => "B")
);
echo $students["GFG"]["age"];
?>
• Creating array in PHP
• In PHP, arrays can be created using two main methods:
• 1. Using the array() function
• The traditional way of creating an array is using the array() function.
$fruits = array("apple", "banana", "cherry");
• 2. Using short array syntax ([])
• In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
$fruits = ["apple", "banana", "cherry"];
• You can also create associative arrays by specifying custom keys:
$person = ["name" => "gfg", "age" => 30];
• Accessing and modifying array elements
1. Accessing array elements
• You can access individual elements in an array using their index (for indexed arrays) or key (for
associative arrays).
• Accessing indexed array:
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // outputs: apple
• Accessing associative array:
$person = ["name" => "GFG", "age" => 30];
echo $person["name"]; // outputs: GFG
• 2. Modifying array elements
• You can modify an existing element by assigning a new value to a specific index or key.
• Modifying Indexed Array Element:
$fruits = ["apple", "banana", "cherry"];
$fruits[1] = "mango"; // changes "banana" to "mango"
echo $fruits[1]; // outputs: mango
• Modifying Associative Array Element:
$person = ["name" => "gfg", "age" => 25];
$person["age"] = 26; // updates the age to 26
echo $person["age"]; // outputs: 26
• Adding and removing array items
1. Adding array elements
• You can add new elements to an array using the following methods:
• array_push(): adds elements to the end of an indexed array.
• Example: $fruits = ["apple", "banana"];
array_push($fruits, "cherry"); // adds "cherry" to the end
• array_unshift(): adds elements to the beginning of an indexed array.
Example: array_unshift($fruits, "pear"); // adds "pear" to the beginning
• Direct assignment: adds an element to an associative array.
Example: $person["city"] = "new york";
2. Removing array elements
• To remove items from an array, you can use several functions:
• array_pop(): removes the last element from an indexed array.
Example: array_pop($fruits);
• array_shift(): removes the first element from an indexed array.
Example: array_shift($fruits);
• unset(): removes a specific element from an array by key or index.
Example: unset($fruits[2]); // removes the element with index 2
• Array 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.
Example: $array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = array_merge($array1, $array2);
print_r($merged); // outputs: [1, 2, 3, 4, 5, 6]
• array search: the in_array() function checks if a specific value exists in an array.
Example: $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.
Example: $numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers); // outputs: [1, 1, 3, 4, 5]
• sizeof() : The sizeof() function is an alias of count(). Both functions return the number of elements in an array or in
an object. It's commonly used to determine the length of an array.
• Syntax: sizeof(array $array, int $mode = COUNT_NORMAL): int
• Example: $list = array(“Bob”,”Fred”, “Alan”, “Bozo”);
$len = sizeof($list);
• explode() - split a string into an array
• The explode() function breaks a string into an array of strings, using a specified delimiter.
• Syntax: explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
• Example: $str = “April in Paris, Texas is nice”;
$words = explode(“ “, $str);
• implode() - join array elements into a string
• The implode() function returns a string from the elements of an array. The array elements will be joined by a
specified string (the glue).
• Syntax: implode(string $separator, array $array): string
• Example: $words = array (“Are”, “you”, “lonesome”, “tonight”);
$str = implode(“ “, $words);
• Sorting array

• Sorting arrays is one of the most common operation in programming, and php provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or
keys, in ascending or descending order. PHP also allows you to create custom sorting functions.

• Sort an array in ascending order - sort() function

• The sort() function is used to sort an array by values in ascending order. It reindexes the array numerically after sorting the array elements. It means the original keys are lost.

• Syntax: sort(array &$array, int $sort_flags = sort_regular);

• Example: <?php

$arr = array(40, 61, 2, 22, 13);

sort($arr);

print_r($arr);

?>

• Sort an array in descending order - rsort() function

• The rsort() function sorts an array by values in descending order. Like sort(), it reindexes the array numerically.

• Syntax: rsort(array &$array, int $sort_flags = sort_regular);

• Example: <?php

$arr = array(40, 61, 2, 22, 13);

rsort($arr);

print_r($arr);

?>
• 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.
• Syntax: asort(array &$array, int $sort_flags = sort_regular);
• Example :<?php
$arr = array(
"Ayush"=>"23",
"Shankar"=>"47",
"Kailash"=>"41“
);
asort($arr);
print_r($arr)
?>
• Sort an array in descending order according to array value - arsort() function
• The arsort() function sorts an array by values in descending order while maintaining the key-value association.
• Syntax: arsort(array &$array, int $sort_flags = sort_regular);
• Example : <?php
$arr = array(
"Ayush"=>"23",
"Shankar"=>"47",
"Kailash"=>"41“
);
arsort($arr);
print_r($arr);
?>
• Sort an array in ascending order according to array key - ksort() function
• The ksort() function sorts an array by keys in ascending order, preserving key-value pairs.
• Syntax: ksort(array &$array, int $sort_flags = sort_regular);
• Example: <?php
$arr = array(
"Ayush"=>"23",
"Shankar"=>"47",
"Kailash"=>"41"
);
ksort($arr);
print_r($arr)
?>
• Sort array in descending order according to array key - krsort() function
• The krsort() function sorts an array by keys in descending order, preserving key-value pairs.
• Syntax: krsort(array &$array, int $sort_flags = sort_regular);
• Example: <?php
$arr = array(
"ayush"=>"23",
"shankar"=>"47",
"kailash"=>"41“
);
krsort($arr);
print_r($arr)
?>
FUNCTIONS IN PHP
• A function in PHP is a self-contained block of code that performs a specific task. It can accept
inputs (parameters), execute a set of statements, and optionally return a value.
• PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.
• Functions can accept parameters and return values, enabling dynamic behavior based on inputs.
• PHP supports both built-in functions and user-defined functions, enhancing flexibility and
modularity in code.
• Creating a function in PHP
• A function is declared by using the function keyword, followed by the name of the function,
parentheses (possibly containing parameters), and a block of code enclosed in curly braces.
• SYNTAX
function functionname($param1, $param2) {
// code to be executed
return $result; // optional
}
• In this syntax:
• Function is a keyword that starts the function declaration.
• Function name is the name of the function.
• $param1 and $param2 are parameters (optional) that can be passed to the function.
• The return statement (optional) sends a value back to the caller.
• Calling a function in PHP
• Once a function is declared, it can be invoked (called) by simply using the function name
followed by parentheses.
<?php
function sum($a, $b) {
return $a + $b;
}
echo sum(5, 3); // outputs: 8
?>
• TYPES OF FUNCTIONS IN PHP
• PHP has two types of functions:
1. USER-DEFINED FUNCTIONS
• A user-defined function is created to perform a specific task as per the developer's need. These
functions can accept parameters, perform computations, and return results.
<?php
function addNumbers($a, $b) {
return $a + $b;
}
echo addNumbers(5, 3); // Output: 8
?>
2. BUILT-IN FUNCTIONS
• PHP comes with many built-in functions that can be directly used in your code. For example,
strlen(), substr(), array_merge(), date() and etc are built-in PHP functions. These functions
provide useful functionalities, such as string manipulation, date handling, and array operations,
without the need to write complex logic from scratch.
• Example
<?php
$str = "Hello, World!";
echo strlen($str); // Output: 13
?>
• PHP function parameters and arguments
• 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.
• 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.
• Example:
<?php
function add($x, $y) {
$x = $x + $y;
return $x;
}
echo add(2, 3); // Outputs: 5
?>
2. Passing by reference
• By passing an argument by reference, any changes made inside the function will affect the
original variable outside the function.
• Example:
<?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.
• Example:
<?php
function multiply($a, $b) {
return $a * $b;
}
$result = multiply(4, 5); // $result will be 20
echo $result; // Output: 20
?>
• THE SCOPE OF VARIABLES
• In PHP, variable scope refers to the context within which a variable is accessible. There are three
main types of variable scopes in PHP:
1. Local scope
• Variables declared inside a function are local to that function.
• They cannot be accessed outside the function.
• EXAMPLE:
function test() {
$x = 10; // local scope
echo $x;
}
test(); // outputs: 10
echo $x; // error: undefined variable
2. GLOBAL SCOPE
• Variables declared outside any function have global scope.
• These cannot be accessed directly inside functions.
• Use the global keyword or $GLOBALS array inside functions to access them.
• Example:
$x = 20;
function test() {
global $x;
echo $x; // Outputs: 20
}
test();
3. STATIC SCOPE
• Variables declared with static inside a function retain their value across multiple calls to that
function.
• Useful for maintaining state information.
• Example:
function counter() {
static $count = 0;
$count++;
echo $count . "\n";
}
counter(); // Outputs: 1
counter(); // Outputs: 2
Scope Declared In Accessible In Keyword to Access
Local Inside function Only inside that function —
Globally, or inside
Global Outside function functions using global or global, $GLOBALS
$GLOBALS
Persists between function
Static Inside function static
calls
• THE LIFE TIME OF VARIABLES
• In PHP, the lifetime of a variable refers to how long the variable exists in memory — from the
time it is created until it is destroyed.
• It depends on the scope and type of the variable.

Type of Variable Life time Begins Life time Ends

Local When function is called When function ends

Global When script starts When script ends

Static First time function is called When script ends

Depends on context ($_SESSION


Superglobal When script starts/request begins
can persist)
PATTERN MATCHING
• Pattern matching in PHP is primarily done using regular expressions (regex) through the preg_
functions. It allows you to search, validate, extract, or replace text based on specific patterns.
• PHP includes two different kinds of string pattern matching using regular expressions:
1. POSIX regular expressions:
• The POSIX regular expressions are compiled into PHP
2. PCER (Perl-Compatible Regular Expression):
• PCRE library must be compiled before Perl regular expressions can be used.
• Pattern matching is the process of comparing a string to a pattern (usually a regex) to determine
if it contains, starts with, ends with, or completely matches a desired format.
• COMMON PATTERN MATCHING FUNCTIONS IN PHP

Function Purpose

preg_match() Checks if a pattern matches a string

preg_match_all() Finds all matches in a string

preg_replace() Replaces matched pattern(s)

preg_split() Splits a string using a pattern


1. preg_match() }

• Checks if a pattern matches a string. // Output: Match found!

• Returns: 2. preg_match_all()
1 if a match is found • Finds all matches of a pattern in a string.
0 if no match • Useful when there are multiple matches.
FALSE on error Example:
Example: $pattern = "/\d+/";
$pattern = "/^hello/"; $text = "There are 4 apples and 12 oranges.";
$text = "hello world"; preg_match_all($pattern, $text, $matches);
if (preg_match($pattern, $text)) {
echo "Match found!"; print_r($matches);
} else {
echo "No match.";
3. Preg_replace() 4. preg_split()

• Searches for a pattern and replaces it with • Splits a string based on a pattern (like a regex
something else. version of explode()).
Example: Example:
$pattern = "/cat/"; $text = "apple, orange; banana|grape";
$replacement = "dog"; $pattern = "/[,;|]\s*/";
$text = "The cat sat on the mat."; $fruits = preg_split($pattern, $text);
echo preg_replace($pattern, $replacement, $text); print_r($fruits);
// Output: The dog sat on the mat.
FORM HANDLING
• Form handling in PHP is the process of collecting user input from HTML forms, processing it
on the server, and providing a response (such as saving to a database or displaying a message).
• Form handling in php is a fundamental aspect of building dynamic web applications. It involves
the process of collecting, processing, and responding to data submitted by users through
HTML forms.
• HTML FORM STRUCTURE
• The first step is to create an HTML form. This form defines the input fields users will interact
with.
• You create a form using the <form> tag.
• EXAMPLE
<form action="process_form.php" method="post">
<label for="name">name:</label>
<input type="text" id="name" name="user_name" required><br><br>
<label for="email">email:</label>
<input type="email" id="email" name="user_email" required><br><br>
<label for="message">message:</label>
<textarea id="message" name="user_message"></textarea><br><br>
<input type="submit" value="submit feedback">
</form>
• Accessing form data in PHP
• Using $_POST or $_GET
• Example:
// process.php
$name = $_POST['username'];
$email = $_POST['email'];
echo "Welcome, $name! Your email is $email.";

• Use $_POST if method="post" in the form.


• Use $_get if method="get" in the form.
• DIFFERENCE BETWEEN POST AND GET

Method Data Sent Visibility Use Case

GET URL Visible Search queries, filters

POST HTTP body Hidden Login, Registration


FILES, TRACKING USERS
• In PHP, "files" refer to various aspects of interacting with the file system on the server. This
includes reading from existing files, writing to files, creating new files, deleting files, managing
directories, and handling file uploads from users.
• Types of file operations in PHP
• Several types of file operations can be performed in PHP:
• Reading files: PHP allows you to read data from files either entirely or line by line.
• Writing to files: you can write data to a file, either overwriting existing content or appending to
the end.
• File metadata: PHP allows you to gather information about files, such as their size, type, and last
modified time.
• File uploading: PHP can handle file uploads via forms, enabling users to submit files to the
server.
• Common file handling functions in PHP
o fopen() - opens a file
o fclose() - closes a file
o fread() - reads data from a file
o fwrite() - writes data to a file
o file_exists() - checks if a file exists
o unlink() - deletes a file

• OPENING AND CLOSING FILES


• Before you can read or write to a file, you need to open it using the fopen() function, which returns a
file pointer resource. Once you're done working with the file, you should close it using fclose() to free
up resources.
Example:
<?php
// open the file in read mode
$file = fopen("gfg.txt", "r");
if ($file) {
echo "file opened successfully!";
fclose($file); // close the file
} else {
echo "failed to open the file.";
}
?>
• File modes in PHP
• Files can be opened in any of the following modes:
• “w" – opens a file for writing only. If the file does not exist, then a new file is created, and if the
file already exists, then the file will be truncated (the contents of the file are erased).
• “r" – file is open for reading only.
• “a" – file is open for writing only. The file pointer points to the end of the file. Existing data in
the file is preserved.
• “w+" – opens file for reading and writing both. If the file does not exist, then a new file is
created, and if the file already exists, then the contents of the file are erased.
• “r+" – file is open for reading and writing both.
• “a+" – file is open for write/read. The file pointer points to the end of the file. Existing data in
the file is preserved. If the file is not there, then a new file is created.
• “x" – new file is created for write only.
• Reading from files
• There are two ways to read the contents of a file in PHP. These are –
1. Reading the entire file
• You can read the entire content of a file using the fread() function or the file_get_contents()
function.
• Example:
<?php
$file = fopen("gfg.txt", "r");
$content = fread($file, filesize("gfg.txt"));
echo $content;
fclose($file);
?>
2. Reading a file line by line
• You can use the fgets() function to read a file line by line.
• Example
<?php
$file = fopen("gfg.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
}
?>
• Writing to files
• You can write to files using the fwrite() function. It writes data to an open file in the specified
mode.
• Example
<?php
// Open the file in write mode
$file = fopen("gfg.txt", 'w');
if ($file) {
$text = "Hello world\n";
fwrite($file, $text);
fclose($file);
}
?>
• Deleting files
• Use the unlink() function to delete the file in PHP.
• Example:
<?php
if (file_exists("gfg.txt")) {
unlink("gfg.txt");
echo "File deleted successfully!";
} else {
echo "File does not exist.";
}
?>
COOKIES, SESSIONS
• A cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved
later.
• Cookies in php are created using the setcookie() function. When a cookie is set, the data is stored in the user’s browser
and sent to the server with each subsequent request made by the browser.
• Syntax: setcookie(name, value, expire, path, domain, security);
• How do cookies work?
• Cookies work in the following ways:
• Setting cookies: A cookie is set using the setcookie() function in PHP. The cookie data is stored on the user’s browser
and sent along with each HTTP request to the server.
• Reading cookies: once a cookie is set, it can be accessed using the $_cookie superglobal array. This allows you to
retrieve cookie values that were set on the user’s browser.
• Expiration of cookies: cookies can be set to expire after a certain period. When a cookie expires, it is automatically
deleted by the browser. Cookies can also be manually deleted by calling the setcookie() function with a past expiration
date.
• Sending cookies to the browser: cookies are sent to the browser as http headers. Since HTTP headers must be sent
before any actual content (HTML, etc.), setcookie() must be called before any output is sent to the browser.
• How to use cookies in PHP?
1. Creating cookies
• Create a cookie named auction_item and assign the value luxury car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60
seconds).
• Example:
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created.";
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
2. Checking whether a cookie is set or not
• It is always advisable to check whether a cookie is set or not before accessing its value. Therefore, to check whether a cookie is set or not, the PHP isset()
function is used. To check whether a cookie "auction_item" is set or not, the isset() function is executed as follows:
• Example :
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
3. Accessing cookie values
• For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an associative array that contains a record
of all the cookies values sent by the browser in the current request. The records are stored as a list where the cookie name is
used as the key. To access a cookie named "auction_item", the following code can be executed.
• Example:
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>

</body>
</html>
4. Deleting cookies
• The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie() function is called by passing the cookie name
and other arguments or empty strings, however, this time, the expiration date is required to be set in the past. To delete a cookie named
"auction_item", the following code can be executed.
• Example:
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted";
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>

</body>
</html>
SESSIONS
• A session in PHP is a mechanism that allows data to be stored and accessed across multiple pages
on a website. When a user visits a website, PHP creates a unique session ID for that user. This
session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The
session ID helps the server associate the data stored in the session with the user during their visit.
• PHP sessions are used to maintain state, meaning they allow data to persist as users navigate
through a site, which would otherwise be stateless (i.e., Each request is independent).
• Example: if a user logs in to a website, their login status can be stored in a session variable. As
the user moves through different pages, the login status can be checked using the session variable.
• HOW DO PHP SESSIONS WORK?
• Session start: when a user accesses a php page, the session gets started with the session_start()
function. This function initiates the session and makes the session data available through the
$_SESSION superglobal array.
• Session variables: data that needs to be carried across different pages is stored in the $_session
array. For example, a user’s name or login status can be stored in this array.
• Session id: PHP assigns a unique session id to every user. This session ID is stored in a cookie in
the user's browser by default. The session ID is used to retrieve the user-specific data on each
page load.
• Session data storage: the session data is stored on the server, not the client side. By default, PHP
stores session data in a temporary file on the server. The location of this storage is determined by
the session. save_path directive in the php.ini file.
• Session termination: sessions can be terminated by calling session_destroy(), which deletes the
session data. Alternatively, a session can be closed using session_write_close() to save the session
data and free up server resources.
• EXAMPLE: page1.php — set session variable
<?php
session_start(); // Start the session
// Store a session variable
$_SESSION["username"] = “MCA";
?>
<!DOCTYPE html>
<html>
<body>
<h2>Page 1</h2>
<p>Session has been started and username is set.</p>
<a href="page2.php">Go to Page 2</a>
</body>
</html>
page2.php — retrieve session variable }

<?php ?>

session_start(); // Resume the session </body>

?> </html>

<!DOCTYPE html> Output: WHEN YOU OPEN page1.php IN BROWSER:

<html> Page 1

<body> Session has been started and username is set.

<h2>Page 2</h2> [Go to Page 2]

<?php AFTER CLICKING THE LINK TO page2.php:

if (isset($_SESSION["username"])) { Page 2

echo "Welcome, " . $_SESSION["username"]; Welcome, MCA

} else {
echo "Session not set!";
USING DATABASES, HANDLING XML
• PHP is commonly used to build dynamic web applications that interact with databases, most often
MySQL or MariaDB. This allows data to be stored, retrieved, updated, and deleted efficiently.
• Basic steps for using a database in PHP
o Connect to the database.
o Run sql queries (select, insert, update, delete).
o Fetch results (if applicable).
o Close the connection.
• PHP functions to work with MySQL
• PHP provides two main extensions to work with MySQL:
o MySQLi (MySQL improved) – recommended
o PDO (PHP data objects)
• Example using MySQLi (procedural style)
🔸 Step 1: Create a database and table
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY
KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Step 2: PHP script to insert and retrieve data $result = mysqli_query($conn, "SELECT * FROM
users");
<?php
echo "<h3>User List:</h3>";
// 1. Connect to the database
while ($row = mysqli_fetch_assoc($result)) {
$conn = mysqli_connect("localhost", "root", "",
"testdb"); echo "ID: " . $row["id"] . " | Name: " .
$row["name"] . " | Email: " . $row["email"] . "<br>";
// Check connection
}
if (!$conn) {
// 4. Close the connection
die("Connection failed: " . mysqli_connect_error());
mysqli_close($conn);
}
?>
// 2. Insert data into table
OUTPUT: User List:
$sql = "INSERT INTO users (name, email) VALUES
('Vinutha', '[email protected]')"; ID: 1 | Name: Vinutha | Email:[email protected]
mysqli_query($conn, $sql);
// 3. Retrieve and display data
HANDLING XML
• PHP provides built-in functions and extensions to read, parse, manipulate, and write XML
data. XML (extensible markup language) is commonly used for configuration files, data exchange
between applications, and web services.
• COMMON WAYS TO HANDLE XML IN PHP

Method Description

SimpleXML Easiest way to read and write XML


Allows full control
DOMDocument
(reading/writing/modifying)
Fast, stream-based XML reader (low
XMLReader
memory use)
• EXAMPLE : Sample XML (data.xml)
<users>
<user>
<name>BIET</name>
<email>[email protected]</email>
</user>
<user>
<name>MCA</name>
<email>[email protected]</email>
</user>
</users>
• PHP script to read XML
<?php
// Load XML file
$xml = simplexml_load_file("data.xml") or die("Error: Cannot load XML");
// Loop through each user
foreach ($xml->user as $user) {
echo "Name: " . $user->name . "<br>";
echo "Email: " . $user->email . "<br><br>";
}
?>
OUTPUT: Name: BIET
Email: [email protected]

Name: MCA
Email: [email protected]

You might also like