0% found this document useful (0 votes)
7 views115 pages

PHP Notes

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It supports various functionalities such as handling dynamic content, database operations, and user access control, and is known for its simplicity and speed compared to other languages. The document also covers PHP's installation, syntax, data types, variables, and operators.

Uploaded by

mohinikatre588
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)
7 views115 pages

PHP Notes

PHP is an open-source, server-side scripting language primarily used for web development, created by Rasmus Lerdorf in 1994. It supports various functionalities such as handling dynamic content, database operations, and user access control, and is known for its simplicity and speed compared to other languages. The document also covers PHP's installation, syntax, data types, variables, and operators.

Uploaded by

mohinikatre588
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/ 115

By Ratnadip T Sir

PHP
Introduction to PHP
PHP is an open-source, interpreted, and object-oriented scripting language that
can be executed at the server-side. PHP is well suited for web development.
Therefore, it is used to develop web applications (an application that executes on
the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995.
PHP 8.1 is the latest version of PHP.
▪ PHP stands for Hypertext Preprocessor.
▪ It is a server-side scripting language.
▪ PHP files can contain text, HTML, CSS, JavaScript, and PHP code
▪ PHP is an interpreted language, i.e., there is no need for compilation.
▪ PHP files have the extension ".php".
▪ PHP is an object-oriented language.
▪ PHP is an open-source scripting language.
▪ PHP is simple and easy to learn language.
▪ It is faster than other scripting languages e.g. asp and JSP.

What Can PHP Do?


PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
▪ It handles dynamic content, database as well as session tracking for the
website.
▪ PHP can create, open, read, write, delete, and close files on the server
▪ PHP can collect form data
▪ PHP can send and receive cookies
▪ PHP can add, delete, modify data in your database
▪ PHP can be used to control user-access
▪ PHP can encrypt data
▪ PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP,
and many more.
1
Page

[Ratnadip Sir : +91 702 079 5007]


History and Evolution of PHP
PHP stands for “PHP: Hypertext Preprocessor” where “Preprocessor” means that
changes happen before the HTML page is created. This converts static webpage
to dynamic webpage with the capacity to interact with databases. The PHP
programming language is commonly used for developing web-based software
applications. However, the use of the language is not limited to web development
and it can also be used for developing GUI applications. As per
http://www.netcraft.com in 2013, PHP found application in over 244 million
websites.
PHP was designed for web development, intended to fill the gap between Server
Side Includes (SSI) and Perl. The language’s roots were laid in 1994 through the
work of Rasmus Lerdorf who scripted a series of Common Gateway Interface
(CGI) binaries in C to maintain his homepage. Gradually, he improved these to
include the ability to interact with databases and web forms and named it PHP/FI
meaning “Personal Home Page/Forms Interpreter”. The first version of PHP/FI
was released in 1995 with syntax, variables and form handling resembling Perl
language. The second version PHP/FI 2 was released in 1997.
The team enlarged in 1997 to include Zeev Suraski and Andi Gutmans who re-
scripted the parser to form the base of PHP3 and renamed it PHP: Hypertext
Preprocessor. The rewriting work continued further and in 1999, it led to the
development of Zend Engine which served as an interpreter for PHP language.
Over the years, the updating of the language has continued and the latest version
PHP 5.6.4 was released in December 2014.

Example #1 Example PHP/FI Code


<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->


<!--ifless $numentries 1-->
Sorry, that record does not exist<p>
<!--endif exit-->
Welcome <!--$user-->!<p>
You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->
2
Page

[Ratnadip Sir : +91 702 079 5007]


Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that are given below:
▪ WAMP for Windows
▪ LAMP for Linux
▪ MAMP for Mac
▪ SAMP for Solaris
▪ FAMP for FreeBSD
▪ XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes
some other components too such as FileZilla, OpenSSL, Webalizer,
OpenSSL, Mercury Mail etc.
If you are on Windows and don't want Perl and other features of XAMPP, you
should go for WAMP. In a similar way, you may use LAMP for Linux and MAMP
for Macintosh.

Download and Install WAMP Server


Download WAMP Server

Download and Install LAMP Server


Download LAMP Server

Download and Install MAMP Server


Download MAMP Server

Download and Install XAMPP Server


Download XAMPP Server
3
Page

[Ratnadip Sir : +91 702 079 5007]


Basic Syntax of PHP
PHP code is start with <?php and ends with ?>
Every PHP statements end with a semicolon (;)
PHP code save with .php extension.
PHP contains some HTML tag and PHP code.
You can place PHP code anywhere in your document.

PHP Syntax:
<?php
// PHP code goes here
?>

PHP files save with .php extension and it contain some HTML and PHP code.

PHP Data Types


PHP data types are used to hold different types of data or values. PHP supports
8 primitive data types that can be categorized further in 3 types:
1. Scalar Types (Predefined)
2. Compound Types (User-Defined)
3. Special Types

Scalar Types (Predefined)


It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string

Compound Types (User-Defined)


1. array
2. object

Special Types
1. resource
2. NULL
4
Page

[Ratnadip Sir : +91 702 079 5007]


PHP boolean
Boolean are the Simplest data type work like switch. It holds only two values:
TRUE (1) or FALSE (0). It is often used with conditional statements. If the
condition is correct, it returns TRUE otherwise FALSE.

Example:
<?php
if(TRUE)
echo "This condition is TRUE.";
if(FALSE)
echo "This condition is FALSE.";
?>

Output:

PHP integer
Integer means numeric data with a negative or positive sign. It holds only whole
numbers, i.e., numbers without fractional part or decimal points.

Rules for integer:


▪ An integer can be either positive or negative.
▪ An integer must not contain decimal point.
▪ Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
▪ The range of an integer must be lie between 2,147,483,648 and
2,147,483,647 i.e., - 2^31 to 2^31.

Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
5

echo "HexaDecimal number: " .$hexa1. "</br>";


Page

?>

[Ratnadip Sir : +91 702 079 5007]


Output:

PHP float
A floating-point number is a number with a decimal point. Unlike integer, it can
hold numbers with a fractional or decimal point, including a negative or positive
sign.

Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:

PHP string
A string is a non-numeric data type. It holds letters or any alphabets, numbers,
and even special characters.
String values must be enclosed either within single quotes or in double quotes.
But both are treated differently. To clarify this, see the example below:

Example:
<?php
$company = "RTSoft";
//both single and double quote statements will treat
//different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
6
Page

?>

[Ratnadip Sir : +91 702 079 5007]


Output:
Hello RTSoft
Hello $company

PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.

Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the
//datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:

PHP Object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.

Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
7

}
Page

$obj = new bike();

[Ratnadip Sir : +91 702 079 5007]


$obj -> model();
?>
Output:

PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store
some function calls or references to external PHP resources. For example - a
database call. It is an external resource.

PHP NULL
Null is a special data type that has only one value: NULL. There is a convention
of writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.

Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Output:

8
Page

[Ratnadip Sir : +91 702 079 5007]


Variable in PHP
In PHP, a variable is declared using a $ sign followed by the variable name. Here,
some important points to know about variables:
▪ As PHP is a loosely typed language, so we do not need to declare the data
types of the variables. It automatically analyses the values and makes
conversions to its correct datatype.
▪ After declaring a variable, it can be reused throughout the code.
▪ Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:


$variablename=value;

Rules for declaring PHP variable:


▪ A variable must start with a dollar ($) sign, followed by the variable name.
▪ It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
▪ A variable name must start with a letter or underscore (_) character.
▪ A PHP variable name cannot contain spaces.
▪ One thing to be kept in mind that the variable name cannot start with a
number or special symbols.
▪ PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.

PHP Variable: Declaring string, integer, and float


Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
9
Page

[Ratnadip Sir : +91 702 079 5007]


Operators in PHP
PHP Operator is a symbol i.e used to perform operations on operands. In simple
words, operators are used to perform operations on variables or values.

PHP Operators can be categorized in following forms:


▪ Arithmetic Operators
▪ Assignment Operators
▪ Comparison Operators
▪ Increment / Decrement Operators
▪ Logical Operators
▪ String Operators
▪ Array Operators
▪ Conditional Assignment Operators.

Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result


+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y


/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y


Result of raising $x to the $y’th
** Exponentiation $x ** $y
power
10
Page

[Ratnadip Sir : +91 702 079 5007]


Comparison Operators
The PHP comparison operators are used to compare two values (number or
string):

Operator Name Example Result


== Equal $x == $y Returns true if $x is equal to $y
Returns true if $x is equal to $y,
=== Identical $x === $y
and they are of the same type
Returns true if $x is not equal to
!= Not equal $x != $y
$y
Returns true if $x is not equal to
<> Not equal $x <> $y
$y
Returns true if $x is not equal to
!== Not identical $x !== $y $y, or they are not of the same
type
Returns true if $x is greater than
> Greater than $x > $y
$y

< Less than $x < $y Returns true if $x is less than $y

Greater than or Returns true if $x is greater than


>= $x >= $y
equal to or equal to $y

Less than or equal Returns true if $x is less than or


<= $x <= $y
to equal to $y
Returns an integer less than,
equal to, or greater than zero,
<=> Spaceship $x <=> $y depending on if $x is less than,
equal to, or greater than $y.
Introduced in PHP 7.
11
Page

[Ratnadip Sir : +91 702 079 5007]


Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

Logical Operators
The PHP logical operators are used to combine conditional statements.

Operator Name Example Result


and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true


True if either $x or $y is true, but not
xor Xor $x xor $y
both
&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

String Operators
PHP has two operators that are specially designed for strings.

Operator Name Example Result


- Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
Concatenation
.= $txt1 .= $txt2 Appends $txt2 to $txt1
assignment
12
Page

[Ratnadip Sir : +91 702 079 5007]


Array Operators
The PHP array operators are used to compare arrays.

Operator Name Example Result


+ Union $x + $y Union of $x and $y
Returns true if $x and $y have the
== Equality $x = = $y
same key/value pairs
Returns true if $x and $y have the
=== Identity $x = = = $y same key/value pairs in the same
order and of the same types
!= Inequality $x ! = $y Returns true if $x is not equal to $y

<> Inequality $x < > $y Returns true if $x is not equal to $y


Returns true if $x is not identical to
!== Non-Identity $x ! = = $y
$y

Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on
conditions:

Operator Name Example Result


Returns the value of $x.
The value of $x is expr2
?: Ternary $x = expr1 ? expr2 : expr3 if expr1 = TRUE.
The value of $x is expr3
if expr1 = FALSE
Returns the value of $x.
The value of $x is expr1
if expr1 exists, and is not
NULL.
?? Null coalescing $x = expr1 ?? expr2
If expr1 does not exist or
is NULL, the value of $x
is expr2.
Introduced in PHP 7
13
Page

[Ratnadip Sir : +91 702 079 5007]


Comments in PHP
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.
Comments can be used to:
▪ Let others understand your code
▪ Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-figure
out what they did.
▪ Comments can remind you of what you were thinking when you wrote the
code
PHP supports several ways of commenting:

Single Line Comments


There are two ways to use single line comments in PHP.
▪ / / (C++ style single line comment)
▪ # (Unix Shell style single line comment)
Syntax for single-line comments:
Syntax:
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment


?>

</body>
</html>
14
Page

[Ratnadip Sir : +91 702 079 5007]


Multi Line Comments
In PHP, we can comments multiple lines also. To do so, we need to enclose all
lines within /* */.
Syntax for multiple-line comments:
Syntax:
<!DOCTYPE html>
<html>
<body>

<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

</body>
</html>

15
Page

[Ratnadip Sir : +91 702 079 5007]


Decision Making in PHP
Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
PHP if else statement is used to test condition. There are various ways to use if
statement in PHP.
▪ if
▪ if-else
▪ if-else-if
▪ nested if
▪ switch

if Statement
PHP if statement allows conditional execution of code. It is executed if condition
is true.
if statement is used to executes the block of code exist inside the if statement only
if the specified condition is true.
Syntax:
if (condition) {
code to be executed if condition is true;
}

Example:
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
16
Page

[Ratnadip Sir : +91 702 079 5007]


if-else Statement
PHP if-else statement is executed whether condition is true or false.
if-else statement is slightly different from if statement. It executes one block of
code if the specified condition is true and another block of code if the condition is
false.
Syntax:
if(condition){
//code to be executed if true
} else{
//code to be executed if false
}
Example:
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output:

17
Page

[Ratnadip Sir : +91 702 079 5007]


if-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if-else
statements. So, we can check multiple conditions using this statement.
Syntax:
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and
condition2 is true
} else{
// Code to be executed if both condition1 and condition2
are false
}
Example:
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
18

}
Page

?>

[Ratnadip Sir : +91 702 079 5007]


Output:

Nested if Statement
The nested if statement contains the if block inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.
Syntax:
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
Example:
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
Output:
19
Page

[Ratnadip Sir : +91 702 079 5007]


Switch Statement
If you want to select one of many blocks of code to be executed, use the Switch
statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax:
switch (expression){
case label1:
//code to be executed if expression = label1;
break;
case label2:
//code to be executed if expression = label2;
break;
default:
//code to be executed if expression is different from both
//label1 and label2;
}
Example:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
20
Page

[Ratnadip Sir : +91 702 079 5007]


Loops in PHP
A Loop can be thought of as something that is wrapped around the PHP code spec,
to make it happen again and again. Often when developing an application, to
execute the same block of code, a specific number of times, a loop statement is
used in the code. In PHP the following statement are available:

▪ for - loops through a block of code a specified number of times.


▪ while - loops through a block of code as long as the specified condition is
true.
▪ do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true.
▪ foreach - loops through a block of code for each element in an array.

for Loop
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop.
This means for loop is used when you already know how many times you want to
execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax
given below:
Syntax:
for(initialization; condition; increment/decrement){
//code to be executed
}
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop
have the following meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is
done only once. This parameter is optional
condition - Evaluate each iteration value. The loop continuously executes until
the condition is false. If TRUE, the loop execution continues, otherwise the
execution of the loop ends.
Increment/decrement - It increments or decrements the value of the variable.
21
Page

[Ratnadip Sir : +91 702 079 5007]


Example:
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:

while loop in PHP


PHP while loop can be used to traverse set of code like for loop. The while loop
executes a block of code repeatedly until the condition is FALSE. Once the
condition gets FALSE, it exits from the body of loop.
It should be used if the number of iterations is not known.
The while loop is also called an Entry control loop because the condition is checked
before entering the loop body. This means that first the condition is checked. If
the condition is true, the block of code will be executed.
Syntax:

while(condition){
// execute this code;
// your code here
}

Alternative Syntax
while(condition):
22

//code to be executed
Page

endwhile;

[Ratnadip Sir : +91 702 079 5007]


Example of while loop
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:

do-while Loop
PHP do-while loop can be used to traverse set of code like php while loop. The
PHP do-while loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several
times. If you have to execute the loop at least once and the number of iterations
is not even fixed, it is recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked
after executing the code.
The do-while loop is very much similar to the while loop except the condition
check. The main difference between both loops is that while loop checks the
condition at the beginning, whereas do-while loop checks the condition at the end
of the loop.
Syntax:
do{
//code to be executed
23

}while(condition);
Page

[Ratnadip Sir : +91 702 079 5007]


Example:
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:

foreach Loop
The foreach loop is used to traverse the array elements. It works only on array
and object. It will issue an error if you try to use it with the variables of different
datatype.
The foreach loop works on elements basis rather than index. It provides an easiest
way to iterate the elements of an array.
In foreach loop, we don't need to increment the value.
Syntax
foreach ($array as $value) {
//code to be executed
}
24
Page

[Ratnadip Sir : +91 702 079 5007]


Example:
<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");

//access array elements using foreach loop


foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>
Output:

PHP Include and Require


PHP allows us to create various elements and functions, which are used several
times in many pages. It takes much time to script these functions in multiple
pages. Therefore, use the concept of file inclusion that helps to include files in
various programs and saves the effort of writing code multiple times.
"PHP allows you to include file so that a page content can be reused many times.
It is very helpful to include files when you want to apply the same HTML or PHP
code to multiple pages of a website." There are two ways to include file in PHP.
1. include
2. require
Both include and require are identical to each other, except failure.
▪ include only generates a warning, i.e., E_WARNING, and continue the
execution of the script.
▪ require generates a fatal error, i.e., E_COMPILE_ERROR, and stop the
execution of the script.
25
Page

[Ratnadip Sir : +91 702 079 5007]


PHP include
PHP include is used to include a file on the basis of given path. You may use a
relative or absolute path of the file.
Syntax
There are two syntaxes available for include:
include 'filename';
Or
include ('filename');
Examples
Let's see a simple PHP include example.
File: menu.html
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Menu</title>
</head>

<body>
<a href="https://www.google.com/">Google</a> |
<a href="https://in.search.yahoo.com/?fr2=inr">Yahoo</a> |
<a href="https://www.bing.com/">Bing</a> |
<a href="https://duckduckgo.com/">DuckDuckGo</a>
</body>

</html>
File: index.php
<!DOCTYPE html>
<html lang="en">
26

<head>
Page

<meta charset="UTF-8">

[Ratnadip Sir : +91 702 079 5007]


<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Menu</title>
</head>

<body>

<?php include("menu.html");

?>

<h1>This is Main Page</h1>


</body>

</html>
Output:

PHP require
PHP require is similar to include, which is also used to include files. The only
difference is that it stops the execution of script if the file is not found whereas
include doesn't.
Syntax:
There are two syntaxes available for require:
require 'filename';
Or
27

require ('filename');
Page

[Ratnadip Sir : +91 702 079 5007]


Example:
File: menu.html
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Menu</title>
</head>

<body>
<a href="https://www.google.com/">Google</a> |
<a href="https://in.search.yahoo.com/?fr2=inr">Yahoo</a> |
<a href="https://www.bing.com/">Bing</a> |
<a href="https://duckduckgo.com/">DuckDuckGo</a>
</body>

</html>
File: index.php
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Menu</title>
</head>

<body>

<?php require("menu.html");
28

?>
Page

[Ratnadip Sir : +91 702 079 5007]


<h1>This is Main Page</h1>
</body>

</html>

29
Page

[Ratnadip Sir : +91 702 079 5007]


Function in PHP
PHP function is a piece of code that can be reused many times. It can take input
as argument list and return value. There are thousands of built-in functions in
PHP.
In PHP, we can define Conditional function, Function within Function and
Recursive function also.
Advantage of PHP Functions
▪ Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.
▪ Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.
▪ Easy to understand: PHP functions separate the programming logic. So it is
easier to understand the flow of the application because every logic is
divided in the form of functions.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the syntax to
declare user-defined functions.
Syntax:
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other
labels in PHP. It can't be start with numbers or special symbols.

PHP Functions Example


File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
30
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Function Arguments
We can pass the information in PHP function through arguments which is
separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument
values and Variable-length argument list.
Let's see the example to pass single argument in PHP function.
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:

Let's see the example to pass two argument in PHP function.


File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
31
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Call By Reference
Value passed to the function doesn't modify the actual value by default (call by
value). But we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a
reference, you need to use ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
File: functionaref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello';
adder($str);
echo $str;
?>
Output:

PHP Function: Default Argument Value


We can specify a default argument value in function. While calling PHP function
if you don't specify any argument, it will take the default argument. Let's see a
simple example of using default argument value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello(); //passing no value
sayHello("John");
?>
Output:
32
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Function: Returning Value
Let's see an example of PHP function that returns value.
File: functiondefaularg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:

PHP Parameterized Function


PHP Parameterized functions are the functions with parameters. You can pass
any number of parameters inside a function. These passed parameters act as
variables inside your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the
function.
PHP Parameterized Example 1
Addition and Subtraction
In this example, we have passed two parameters $x and $y inside two functions
add() and sub().
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
//Adding two numbers
function add($x, $y) {
33

$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
Page

[Ratnadip Sir : +91 702 079 5007]


add(467, 943);

//Subtracting two numbers


function sub($x, $y) {
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</html>
Output:

PHP Parameterized Example 2


Addition and Subtraction with Dynamic number.
In this example, we have passed two parameters $x and $y inside two functions
add() and sub().
<?php
//add() function with two parameter
function add($x,$y)
{
$sum=$x+$y;
echo "Sum = $sum <br><br>";
34

}
//sub() function with two parameter
Page

function sub($x,$y)

[Ratnadip Sir : +91 702 079 5007]


{
$sub=$x-$y;
echo "Diff = $sub <br><br>";
}
//call function, get two argument through input box and
click on add or sub button
if(isset($_POST['add']))
{
//call add() function
add($_POST['first'],$_POST['second']);
}
if(isset($_POST['sub']))
{
//call add() function
sub($_POST['first'],$_POST['second']);
}
?>
<form method="post">
Enter first number: <input type="number"
name="first"/><br><br>
Enter second number: <input type="number"
name="second"/><br><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
</form>
Output:

35
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Call By Value
PHP allows you to call function by value and reference both. In case of PHP call
by value, actual value is not modified if it is modified inside the function.
Let's understand the concept of call by value by the help of examples.
Example
In this example, variable $str is passed to the adder function where it is
concatenated with 'Call By Value' string. But, printing $str variable results 'Hello'
only. It is because changes are done in the local variable $str2 only. It doesn't
reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:

PHP Call By Reference


In case of PHP call by reference, actual value is modified if it is modified inside
the function. In such case, you need to use & (ampersand) symbol with formal
arguments. The & represents reference of the variable.
Let's understand the concept of call by reference by the help of examples.
Example
In this example, variable $str is passed to the adder function where it is
concatenated with 'Call By Reference' string. Here, printing $str variable results
'This is Call By Reference'. It is because changes are done in the actual variable
$str.
36
Page

[Ratnadip Sir : +91 702 079 5007]


<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:

PHP Default Argument Values Function


PHP allows you to define C++ style default argument values. In such case, if you
don't pass any value to the function, it will use default argument value.
Let' see the simple example of using PHP default arguments in function.
Example:
<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>
Output: 37
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Variable Length Argument Function
PHP supports variable length argument function. It means you can pass 0, 1 or n
number of arguments in function. To do so, you need to use 3 ellipses (dots) before
the argument name.
The 3-dot concept is implemented for variable length argument since PHP 5.6.
Let's see a simple example of PHP variable length argument function.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}

echo add(1, 2, 3, 4);


?>
Output:

PHP Recursive Function


PHP also supports recursive function call like C/C++. In such case, we call current
function within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because
it may smash the stack and may cause the termination of script.
Example:
<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
38

display(1);
Page

?>

[Ratnadip Sir : +91 702 079 5007]


Output:

PHP Variable Scope


The scope of a variable is defined as its range in the program under which it can
be accessed. In other words, "The scope of a variable is the portion of the program
within which it is defined and can be accessed."
PHP has three types of variable scopes:
1. Local Variable
2. Global Variable
3. Static Variable

Local Variable
The variables that are declared within a function are called local variables for
that function. These local variables have their scope only in that particular
function in which they are declared. This means that these variables cannot be
accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely
different from the variable declared inside the function. Let's understand the local
variables with the help of an example:
File: localvariable1.php
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is:
". $num;
}
local_var();
39

?>
Page

[Ratnadip Sir : +91 702 079 5007]


Output:

File: localvariable2.php
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
//using $lang (local variable) outside the function will
generate an error
echo $lang;
?>
Output:

Global variable
The global variables are the variables that are declared outside the function.
These variables can be accessed anywhere in the program. To access the global
variable within a function, use the GLOBAL keyword before the variable.
However, these variables can be directly accessed or used outside the function
without any keyword. Therefore there is no need to use any keyword to access a
global variable outside the function.
Let's understand the global variables with the help of an example:
Example
File: global_variable1.php
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
40

global $name;
Page

echo "Variable inside the function: ". $name;

[Ratnadip Sir : +91 702 079 5007]


echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:

Note: Without using the global keyword, if you try to access a global variable
inside the function, it will generate an error that the variable is undefined.
Example:
File: global_variable2.php
<?php
$name = "Sanaya Sharma"; //global variable
function global_var()
{
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
?>
Output:

Using $GLOBALS instead of global


Another way to use the global variable inside the function is predefined
$GLOBALS array.
Example:
File: global_variable3.php
<?php
41

$num1 = 5; //global variable


$num2 = 13; //global variable
Page

function global_var()

[Ratnadip Sir : +91 702 079 5007]


{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>
Output:

If two variables, local and global, have the same name, then the local variable has
higher priority than the global variable inside the function.
Example:
File: global_variable2.php
<?php
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Output:

Note: local variable has higher priority than the global variable.
Static variable
It is a feature of PHP to delete the variable, once it completes its execution and
memory is freed. Sometimes we need to store a variable even after completion of
function execution. Therefore, another important feature of variable scoping is
static variable. We use the static keyword before the variable to define a variable,
and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after
42

the program execution leaves the scope. Understand it with the help of an
Page

example:

[Ratnadip Sir : +91 702 079 5007]


Example:
File: static_variable.php
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}

//first function call


static_var();

//second function call


static_var();
?>
Output:

You have to notice that $num1 regularly increments after each function call,
whereas $num2 does not. This is why because $num1 is not a static variable, so
it freed its memory after the execution of each function call.

Anonymous Functions
The function that can be created without any specific name and used as an input
argument in the PHP script, is known as anonymous function. These functions
are implemented using Closure class. The process of assigning an anonymous
function to a variable is same as any other assignment syntax. By passing a
43

variable from parent scope to the use language construct, an anonymous function
Page

from child scope, can inherit the variable.

[Ratnadip Sir : +91 702 079 5007]


PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text.
PHP supports only 256-character set and so that it does not offer native Unicode
support. There are 4 ways to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)

Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify
a literal backslash (\) use double backslash (\\). All the other instances with
backslash such as \r or \n, will be output same as they specified instead of having
any special meaning.
For Example
Following some examples are given to understand the single quoted PHP String
in a better way:
Example 1
<?php
$str='Hello text within single quote';
echo $str;
?>
Output:

Example 2
<?php
$str1='Hello text
multiple line
text within single quoted string';
44

$str2='Using double "quote" directly inside single quoted


string';
Page

$str3='Using escape sequences \n in single quoted string';

[Ratnadip Sir : +91 702 079 5007]


echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:

Example 3:
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single
quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:

Note: In single quoted PHP strings, most escape sequences and variables will not
be interpreted. But, we can use single quote through \' and backslash through \\
inside single quoted PHP strings.
Double Quoted
In PHP, we can specify string through enclosing text within double quote also.
But escape sequences and variables will be interpreted using double quote PHP
strings.
Example 1:
<?php
$str="Hello text within double quote";
echo $str;
?>
45
Page

[Ratnadip Sir : +91 702 079 5007]


Output:

Now, you can't use double quote directly inside double quoted string.
Example 2
<?php
$str1="Using double "quote" directly inside double quoted
string";
echo $str1;
?>
Output:

We can store multiple line text, special characters and escape sequences in a
double quoted PHP string.
Example 3
<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double
quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
46
Page

[Ratnadip Sir : +91 702 079 5007]


Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an
identifier is provided after this heredoc <<< operator, and immediately a new line
is started to write any text. To close the quotation, the string follows itself and
then again that same identifier is provided. That closing identifier must begin
from the new line without any whitespace or tab.

Naming Rules
The identifier should follow the naming rule that it must contain only
alphanumeric characters and underscores, and must start with an underscore or
a non-digit character.
For Example
Valid Example
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid
before closing identifier
echo $str;
?>
Output:

Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon,
which means identifier must not be indented. The identifier must begin from the
new line.
<?php
$str = <<<Demo
It is Invalid example
Demo; //Invalid code as whitespace or tab is not
valid before closing identifier
echo $str;
?>
47

This code will generate an error.


Page

[Ratnadip Sir : +91 702 079 5007]


Output:

Heredoc is similar to the double-quoted string, without the double quote, means
that quote in a heredoc are not required. It can also print the variable's value.
Example
<?php
$city = 'Delhi';
$str = <<<DEMO
Hello! My name is Misthi, and I live in $city.
DEMO;
echo $str;
?>
Output:

Example:
We can add multiple lines of text here between heredoc syntax.
<?php
$str = <<<DEMO
It is the example
of multiple
lines of text.
DEMO;
echo $str;

echo '</br>';

echo <<<DEMO // Here we are not storing string content


in variable str.
It is the example
of multiple
lines of text.
DEMO;
48

?>
Page

[Ratnadip Sir : +91 702 079 5007]


Output:

Below are the example with class and their variable


<?php
class heredocExample{
var $demo;
var $example;
function __construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2',
'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';
echo <<<ECO
My name is "$name". I am printing some $heredocExample-
>demo example.
Now, I am printing {$heredocExample->example[1]}.
It will print a capital 'A': \x41
ECO;
?>
Output:

49
Page

[Ratnadip Sir : +91 702 079 5007]


Encoding and Escaping
Because PHP programs often interact with HTML pages, web addresses (URLs),
and databases, there are functions to help you work with those types of data.
HTML, web page addresses, and database commands are all strings, but they
each require different characters to be escaped in different ways. For instance, a
space in a web address must be written as %20, while a literal less-than sign (<)
in an HTML document must be written as &lt;. PHP has a number of built-in
functions to convert to and from these encodings.

HTML
Special characters in HTML are represented by entities such as &amp; and &lt;.
There are two PHP functions that turn special characters in a string into their
entities: one for removing HTML tags, and one for extracting only meta tags.

Entity-quoting all special characters


The htmlentities() function changes all characters with HTML entity equivalents
into those equivalents (with the exception of the space character). This includes
the less-than sign (<), the greater-than sign (>), the ampersand (&), and accented
characters.
For example:
$string = htmlentities("Einstürzende Neubauten");
echo $string;
Einstürzende Neubauten
The entity-escaped version (&uuml;—seen by viewing the source) correctly
displays as ü in the rendered web page. As you can see, the space has not been
turned into &nbsp;.
The htmlentities() function actually takes up to three arguments:
$output = htmlentities(input, quote_style, charset);
The charset parameter, if given, identifies the character set. The default is “ISO-
8859-1.” The quote_style parameter controls whether single and double quotes are
turned into their entity forms. ENT_COMPAT (the default) converts only double
quotes, ENT_QUOTES converts both types of quotes, and ENT_NOQUOTES
converts neither. There is no option to convert only single quotes.
50
Page

[Ratnadip Sir : +91 702 079 5007]


For example:
$input = <<< End
"Stop pulling my hair!" Jane's eyes flashed.<p>
End;

$double = htmlentities($input);
// &quot;Stop pulling my hair!&quot; Jane's eyes
flashed.&lt;p&gt;

$both = htmlentities($input, ENT_QUOTES);


// &quot;Stop pulling my hair!&quot; Jane&#039;s eyes
flashed.&lt;p&gt;

$neither = htmlentities($input, ENT_NOQUOTES);


// "Stop pulling my hair!" Jane's eyes flashed.&lt;p&gt;
Entity-quoting only HTML syntax characters
The htmlspecialchars() function converts the smallest set of entities possible to
generate valid HTML. The following entities are converted:
▪ Ampersands (&) are converted to &amp;
▪ Double quotes (") are converted to &quot;
▪ Single quotes (') are converted to &#039; (if ENT_QUOTES is on, as
described for htmlentities())
▪ Less-than signs (<) are converted to &lt;
▪ Greater-than signs (>) are converted to &gt;
If you have an application that displays data that a user has entered in a form,
you need to run that data through htmlspecialchars() before displaying or saving
it. If you don’t, and the user enters a string like "angle < 30" or "sturm & drang",
the browser will think the special characters are HTML, resulting in a garbled
page.
Like htmlentities(), htmlspecialchars() can take up to three arguments:
$output = htmlspecialchars(input, [quote_style, [charset]]);
51
Page

[Ratnadip Sir : +91 702 079 5007]


The quote_style and charset arguments have the same meaning that they do for
htmlentities().
There are no functions specifically for converting back from the entities to the
original text, because this is rarely needed. There is a relatively simple way to do
this, though. Use the get_html_translation_table() function to fetch the
translation table used by either of these functions in a given quote style. For
example, to get the translation table that htmlentities() uses, do this:
$table = get_html_translation_table(HTML_ENTITIES);
To get the table for htmlspecialchars() in ENT_NOQUOTES mode, use:
$table = get_html_translation_table(HTML_SPECIALCHARS,
ENT_NOQUOTES);
A nice trick is to use this translation table, flip it using array_flip(), and feed it to
strtr() to apply it to a string, thereby effectively doing the reverse of htmlentities():
$str = htmlentities("Einstürzende Neubauten"); // now it is
encoded

$table = get_html_translation_table(HTML_ENTITIES);
$revTrans = array_flip($table);

echo strtr($str, $revTrans); // back to normal


Einstürzende Neubauten
You can, of course, also fetch the translation table, add whatever other
translations you want to it, and then do the strtr().
For example, if you wanted htmlentities() to also encode spaces to &nbsp;s, you
would do:
$table = get_html_translation_table(HTML_ENTITIES);
$table[' '] = '&nbsp;';
$encoded = strtr($original, $table);
Removing HTML tags
The strip_tags() function removes HTML tags from a string:
$input = '<p>Howdy, &quot;Cowboy&quot;</p>';
$output = strip_tags($input);
// $output is 'Howdy, &quot;Cowboy&quot;'
52
Page

[Ratnadip Sir : +91 702 079 5007]


The function may take a second argument that specifies a string of tags to leave
in the string. List only the opening forms of the tags. The closing forms of tags
listed in the second parameter are also preserved:
$input = 'The <b>bold</b> tags will <i>stay</i><p>';
$output = strip_tags($input, '<b>');
// $output is 'The <b>bold</b> tags will stay'
Attributes in preserved tags are not changed by strip_tags(). Because attributes
such as style and onmouseover can affect the look and behavior of web pages,
preserving some tags with strip_tags() won’t necessarily remove the potential for
abuse.

Extracting meta tags


The get_meta_tags() function returns an array of the meta tags for an HTML
page, specified as a local filename or URL. The name of the meta tag (keywords,
author, description, etc.) becomes the key in the array, and the content of the meta
tag becomes the corresponding value:
$metaTags = get_meta_tags('http://www.example.com/');
echo "Web page made by {$metaTags['author']}";
//Output : Web page made by John Doe
URLs
PHP provides functions to convert to and from URL encoding, which allows you
to build and decode URLs. There are actually two types of URL encoding, which
differ in how they treat spaces. The first (specified by RFC 3986) treats a space as
just another illegal character in a URL and encodes it as %20. The second
(implementing the application/x-www-form-urlencoded system) encodes a space
as a + and is used in building query strings.
Note that you don’t want to use these functions on a complete URL, such as
http://www.example.com/hello, as they will escape the colons and slashes to
produce:
http%3A%2F%2Fwww.example.com%2Fhello
Only encode partial URLs (the bit after http://www.example.com/) and add the
protocol and domain name later.
53
Page

[Ratnadip Sir : +91 702 079 5007]


Comparing String
Operators
One can compare two strings for equality with the = = and = = = operators:
1) Equality (= =): The = = (equal to) operator is true if its arguments are exactly
equal but false otherwise. If both operands are equal, this operator returns
true; otherwise, it returns false.
2) Identity (= = =): The === operator (identical to) is true if its two arguments
are exactly equal and of the same type. If both operands are equal and are
of the same type, this operator return true; otherwise, it returns false.

Note that this operator does not do implicit type casting. This operator is
useful when one does not know if the values, he/she is comparing are of the
same type. Simple comparison may value conversion. Involve
For example, the strings "0.0" and "0" are not equal. The == operator says
they are, but === says they are not.
The comparison operators (<, <=, >, >=) also work on strings:
i. Greater than (>): If the left hand operand is greater than the right hand
operand, this operator returns true; otherwise, it returns false.
ii. Greater than or equal to (>=): If the left-hand operand is greater than or
equal to the right-hand operand, this operator returns true; otherwise, it
returns false.
iii. Less than (<): If the left-hand operand is less than the right-hand operand,
this operator returns true; otherwise, it returns false.
iv. Less than or equal to (<=): If the left-hand operand is less than or equal to
the right-hand operand, this operator returns true; otherwise, it returns
false.

Comparing Functions
Comparison Functions Some functions are as below:
1) strcmp(): The strcmp function compares the first string to the second string.
Comparisons are made by ASII values. This function is safe for comparing
binary data.
Syntax: strcmp(string 1, string_2):
The function returns a number less than 0 if string 1 sorts before string 2. greater
54

than 0 if string 2 sorts before string 1, or 0 if they are the same.


Page

[Ratnadip Sir : +91 702 079 5007]


2) strcasecmp(): A variation on strcmp() is strcasecmp(), which converts strings
to lowercase before comparing them. Its arguments and return values are
the same as those for strcmp(). The strcasecmp function operates identically
to stremp except that it treats uppercase and lowercase as identical.
For Example: let consider the following code:
$n = strcasecmp(“Fred”, frED“”); //$n in 0;
3) strncmp(): Another variation on string comparison is to compare only the
first few characters of the string. The strcmp() functions take an additional
argument, the initial number of characters to use for the comparisons.
The strncmp function compares the first parts of two strings. PHP compares
the strings, character by character, until comparing the number of
characters specified by length or reaching the end of one of the strings. PHP
considers order based on ASCII value.
If first and second are equal. PHP returns zero. If first comes before second.
PHP returns a negative number. If second comes before first, PHP returns
a positive number.
Syntax:
integer strncmp (string first, string second, integer length)
4) strncasecmp(): One can use strncasecmp to compare the first parts of two
strings. PHP compares the strings, character by character, until comparing
the number of characters specified by length or reaching the end of one of
the strings. PHP treats letters of different case as equal. If first and second
are equal. PHP returns zero. If first comes before second. PHP returns a
negative number. If second comes before first. PHP returns a positive
number.
Syntax:
integer strncasecmp (string first, string second, integer length)
5) strnatcmp() and strnatcasecmp(): The final variation on these functions is
natural-order comparison with stratcmp() and stratcasecmp(). which take
the same arguments as strcmp() and return the same kinds of values.
Natural-order comparison identifies numeric portions of the strings being
compared and sorts the string parts separately from the numeric parts.
Syntax:
strnatcasecmp(string1, string2)
This function returns:
i) 0 : If the two strings are equal.
ii) <0 : If string1 is less than string2
55

iii) >0 : If string1 is grater than string2


Page

[Ratnadip Sir : +91 702 079 5007]


Manipulating and Searching String
PHP provides many built-in functions for manipulating strings like calculating
the length of a string, find substrings or characters, replacing part of a string with
different characters, take a string apart, and many others.
The functions responsible for the manipulation and searching of string are given
below:
1) strlen()
2) strstr()
3) strops()
4) strrev()
5) str_pad()
6) strtok()
7) str_repeat()
8) explode()
9) sscanf()
10) strops() and strops()
11) strstr(), strchr() and friends
12) strspn() and strcspn()

Substrings Functions
1) strtolower() function: The strtolower() function returns string in lowercase
letter.
Syntax: string strtolower ( string $string )
Example:
<?php
$str="My name is KHAN";
$str=strtolower($str);
echo $str;
?>
Output:
56
Page

[Ratnadip Sir : +91 702 079 5007]


2) strtoupper() function: The strtoupper() function returns string in
uppercase letter.
System: string strtoupper ( string $string )
Example:
<?php
$str="My name is KHAN";
$str=strtoupper($str);
echo $str;
?>
Output:

3) ucfirst() function: The ucfirst() function returns string converting first


character into uppercase. It doesn't change the case of other characters.
Syntax: string ucfirst ( string $str )
Example:
<?php
$str="my name is KHAN";
$str=ucfirst($str);
echo $str;
?>
Output:

4) lcfirst() function : The lcfirst() function returns string converting first


character into lowercase. It doesn't change the case of other characters.
Syntax: string lcfirst ( string $str )
Example:
<?php
$str="MY name IS KHAN";
$str=lcfirst($str);
57

echo $str;
Page

?>

[Ratnadip Sir : +91 702 079 5007]


Output:

5) ucwords() function: The ucwords() function returns string converting first


character of each word into uppercase.
Syntax: string ucwords ( string $str )
Example:
<?php
$str="my name is Sonoo jaiswal";
$str=ucwords($str);
echo $str;
?>
Output:

6) strrev() function: The strrev() function returns reversed string.


Syntax: string strrev ( string $string )
Example:
<?php
$str="my name is Sonoo jaiswal";
$str=strrev($str);
echo $str;
?>
Output:

7) strlen() function: The strlen() function returns length of the string.


Syntax: int strlen ( string $string )
Example:
<?php
58

$str="my name is Sonoo jaiswal";


Page

$str=strlen($str);

[Ratnadip Sir : +91 702 079 5007]


echo $str;
?>
Output:

Regular Expression
Regular expressions are nothing more than a sequence or pattern of characters
itself. They provide the foundation for pattern-matching functionality.
Using regular expression, you can search a particular string inside another string,
you can replace one string by another string and you can split a string into many
chunks.
PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression. You can use any of them
based on your comfort.
▪ POSIX Regular Expressions
▪ PERL Style Regular Expressions

POSIX Regular Expressions


The structure of a POSIX regular expression is not dissimilar to that of a typical
arithmetic expression: various elements (operators) are combined to form more
complex expressions
The simplest regular expression is one that matches a single character, such as g,
inside strings such as g, haggle, or bag.
Let’s give explanation for few concepts being used in POSIX regular expression.
After that we will introduce you with regular expression related functions.

Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.

Sr. No Expression & Description


[0-9]
1
It matches any decimal digit from 0 through 9.
59

2 [a-z]
Page

[Ratnadip Sir : +91 702 079 5007]


It matches any character from lower-case a through
lowercase z.
[A-Z]
3 It matches any character from uppercase A through
uppercase Z.
[a-Z]
4 It matches any character from lowercase a through
uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.

Quantifiers
The frequency or position of bracketed character sequences and single characters
can be denoted by a special character. Each special character having a specific
connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.

Sr. No Expression & Description


p+
1
It matches any string containing at least one p.
p*
2
It matches any string containing zero or more p’s.
p?
3
It matches any string containing zero or one p’s.
p{N}
4
It matches any string containing a sequence of N p’s.
p{2, 3}
5 It matches any string containing a sequence of two or three
p’s.
p{2, }
6 It matches any string containing a sequence of at least two
p’s.
p$
7
It matches any string with p at the end of it.
60

^p
8
Page

It matches any string with p at the beginning of it.

[Ratnadip Sir : +91 702 079 5007]


Example:
Following examples will clear your concepts about matching characters.

Sr. No Expression & Description


[^a-zA-Z]
1 It matches any string not containing any of the characters
ranging from a through z and A through Z.
p.p
2 It matches any string containing p, followed by any
character, in turn followed by another p.
^.{2}$
3
It matches any string containing exactly two characters.
<b>(.*)</b>
4
It matches any string enclosed within <b> and </b>.
p(hp)*
5 It matches any string containing a p followed by zero or
more instances of the sequence php.
Predefined Character Ranges
For your programming convenience several predefined character
ranges, also known as character classes, are available. Character
classes specify an entire range of characters, for example, the alphabet
or an integer set –

Sr. No Expression & Description


[[:alpha:]]
1 It matches any string containing alphabetic characters aA
through zZ.
[[:digit:]]
2 It matches any string containing numerical digits 0 through
9.
[[:alnum:]]
3 It matches any string containing alphanumeric characters aA
61

through zZ and 0 through 9.


Page

[Ratnadip Sir : +91 702 079 5007]


[[:space:]]
4
It matches any string containing a space.

PHP's Regexp POSIX Functions


PHP currently offers seven functions for searching strings using
POSIX-style regular expressions –

Sr. No Function & Description


ereg()
The ereg() function searches a string specified by string for
1
a string specified by pattern, returning true if the pattern
is found, and false otherwise.
ereg_replace()
2 The ereg_replace() function searches for string specified by
pattern and replaces pattern with replacement if found.
eregi()
The eregi() function searches throughout a string specified
3
by pattern for a string specified by string. The search is not
case sensitive.
eregi_replace()
The eregi_replace() function operates exactly like
4
ereg_replace(), except that the search for pattern in string
is not case sensitive.
split()
The split() function will divide a string into various
5
elements, the boundaries of each element based on the
occurrence of pattern in string.
spliti()
6 The spliti() function operates exactly in the same manner
as its sibling split(), except that it is not case sensitive.
sql_regcase()
7 The sql_regcase() function can be thought of as a utility
62

function, converting each character in the input parameter


Page

[Ratnadip Sir : +91 702 079 5007]


string into a bracketed expression containing two
characters.

PERL Style Regular Expressions

Perl-style regular expressions are similar to their POSIX counterparts.


The POSIX syntax can be used almost interchangeably with the Perl-
style regular expression functions. In fact, you can use any of the
quantifiers introduced in the previous POSIX section.

Lets give explanation for few concepts being used in PERL regular
expressions. After that we will introduce you wih regular expression
related functions.

Meta characters

A meta character is simply an alphabetical character preceded by a


backslash that acts to give the combination a special meaning.

For instance, you can search for large money sums using the '\d' meta
character: /([\d]+)000/, Here \d will search for any string of numerical
character.

Following is the list of meta characters which can be used in PERL Style
Regular Expressions.
Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given
set
(foo|bar|baz) matches any of the alternatives specified
63
Page

[Ratnadip Sir : +91 702 079 5007]


Modifiers
Several modifiers are available that can make your work with regexps
much easier, like case sensitivity, searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for
clarity
g Globally finds all matches
cg Allows a search to continue even after a global match
fails
PHP's Regexp PERL Compatible Functions

Sr. No Function & Description


preg_match()
1 The preg_match() function searches string for pattern,
returning true if pattern exists, and false otherwise.
preg_match_all()
2 The preg_match_all() function matches all occurrences of
pattern in string.
preg_replace()
The preg_replace() function operates just like
3
ereg_replace(), except that regular expressions can be used
in the pattern and replacement input parameters.
preg_split()
The preg_split() function operates exactly like split(), except
4
that regular expressions are accepted as input parameters
for pattern.
64

5 preg_grep()
Page

[Ratnadip Sir : +91 702 079 5007]


The preg_grep() function searches all elements of
input_array, returning all elements matching the regexp
pattern.
preg_ quote()
6
Quote regular expression characters.

65
Page

[Ratnadip Sir : +91 702 079 5007]


Arrays
PHP array is an ordered map (contains value on the basis of key). It is
used to hold multiple values of similar type in a single variable.
An array is a special variable that we use to store or hold more than one
value in a single variable without having to create more variables to
store those values.
To create an array in PHP, we use the array function array( ).
By default, an array of any variable starts with the 0 index. So
whenever you want to call the first value of an array you start with 0
then the next is 1...and so on.
Advantage of PHP Array
▪ Less Code: We don't need to define multiple variables.
▪ Easy to Traverse: By the help of single loop, we can traverse all
the elements of an array.
▪ Sorting: We can sort the elements of array.
Array Types
There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
Indexed Array
PHP indexed array is an array which is represented by an index
number by default. All elements of array are represented by an index
number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP
indexed array is also known as numeric array.
66
Page

[Ratnadip Sir : +91 702 079 5007]


Definition
There are two ways to define indexed array:
1St Way:
$size=array("Big","Medium","Short");
2nd Way:
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
Indexed Array Example
File: array1.php
<?php
$size=array("Big","Medium","Short");
echo "Size: $size[0], $size[1] and $size[2]";
?>
Output:

File: array2.php
<?php
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
?>
Output:

Traversing Indexed Array


We can easily traverse array in PHP using foreach loop. Let's see a
simple example to traverse all the elements of PHP array.
67
Page

[Ratnadip Sir : +91 702 079 5007]


File: array3.php
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Output:

Count Length of Indexed Array


PHP provides count() function which returns length of an array.
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Output:

Associative Array
PHP allows you to associate name/label with each array elements in
PHP using => symbol. Such way, you can easily remember the element
because each element is represented by label than an incremented
number.
68
Page

[Ratnadip Sir : +91 702 079 5007]


Definition.
There are two ways to define associative array:
1st Way
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"20
0000");
2nd Way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
Example:
File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=
>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
Output:

File: arrayassociative2.php
<?php
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
69

?>
Page

[Ratnadip Sir : +91 702 079 5007]


Output:

Traversing Associative Array


By the help of PHP for each loop, we can easily traverse the elements
of PHP associative array.
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=
>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
Output:

Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows
you to store tabular data in an array. PHP multidimensional array can
be represented in the form of matrix which is represented by row *
column.
Definition:
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
70

);
Page

[Ratnadip Sir : +91 702 079 5007]


Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display
following tabular data. In this example, we are displaying 3 rows and 3
columns.

Id Name Salary

1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

for($row = 0; $row < 3; $row++) {


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
Output:
71
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Array Functions
PHP Array Functions allow you to interact with and manipulate arrays
in various ways. PHP arrays are essential for storing, managing, and
operating on sets of variables.
PHP supports simple and multi-dimensional arrays and may be either
user created or created by another function.
Following table lists down all the functions related to PHP Array. Here
column version indicates the earliest version of PHP that supports the
function.

Sr.No Function & Description Version


array()
1 4.2.0
Create an array
array_change_key_case()
2 Returns an array with all keys in lowercase or 4.2.0
uppercase
array_chunk()
3 4.2.0
Splits an array into chunks of arrays
array_column()
3 Return the values from a single column in the input 5.5.0
array
array_combine()
4 Creates an array by using one array for keys and 5
another for its values
array_count_values()
5 Returns an array with the number of occurrences 4
for each value
array_diff()
6 4
Compares array values, and returns the differences
array_diff_assoc()
7 Compares array keys and values, and returns the 4
72

differences
Page

[Ratnadip Sir : +91 702 079 5007]


array_diff_key()
8 5
Compares array keys, and returns the differences
array_diff_uassoc()
Compares array keys and values, with an additional
9 5
user-made function check, and returns the
differences
array_diff_ukey()
10 Compares array keys, with an additional user-made 5
function check, and returns the differences
array_fill()
11 4
Fills an array with values
array_fill_keys()
12 5
Fill an array with values, specifying keys
array_filter()
13 Filters elements of an array using a user-made 4
function
array_flip()
14 Exchanges all keys with their associated values in 4
an array
array_intersect()
15 4
Compares array values, and returns the matches
array_intersect_assoc()
16 Compares array keys and values, and returns the 4
matches
array_intersect_key()
17 5
Compares array keys, and returns the matches
array_intersect_uassoc()
18 Compares array keys and values, with an additional 5
user-made function check, and returns the matches
array_intersect_ukey()
19 Compares array keys, with an additional user-made 5
73

function check, and returns the matches


Page

20 array_key_exists() 4

[Ratnadip Sir : +91 702 079 5007]


Checks if the specified key exists in the array
array_keys()
21 4
Returns all the keys of an array
array_map()
22 Sends each value of an array to a user-made 4
function, which returns new values
array_merge()
23 4
Merges one or more arrays into one array
array_merge_recursive()
24 4
Merges one or more arrays into one array
array_multisort()
25 4
Sorts multiple or multi-dimensional arrays
array_pad()
26 Inserts a specified number of items, with a specified 4
value, to an array
array_pop()
27 4
Deletes the last element of an array
array_product()
28 5
Calculates the product of the values in an array
array_push()
29 4
Inserts one or more elements to the end of an array
array_rand()
30 4
Returns one or more random keys from an array
array_reduce()
31 Returns an array as a string, using a user-defined 4
function
array_reverse()
32 4
Returns an array in the reverse order
array_search()
33 Searches an array for a given value and returns the 4
key
74

34 array_shift() 4
Page

[Ratnadip Sir : +91 702 079 5007]


Removes the first element from an array, and
returns the value of the removed element
array_slice()
35 4
Returns selected parts of an array
array_splice()
36 Removes and replaces specified elements of an 4
array
array_sum()
37 4
Returns the sum of the values in an array
array_udiff()
38 Compares array values in a user-made function and 5
returns an array
array_udiff_assoc()
39 Compares array keys, and compares array values in 5
a user-made function, and returns an array
array_udiff_uassoc()
40 Compares array keys and array values in user-made 5
functions, and returns an array
array_uintersect()
41 Compares array values in a user-made function and 5
returns an array
array_uintersect_assoc()
42 Compares array keys, and compares array values in 5
a user-made function, and returns an array
array_uintersect_uassoc()
43 Compares array keys and array values in user-made 5
functions, and returns an array
array_unique()
44 4
Removes duplicate values from an array
array_unshift()
45 Adds one or more elements to the beginning of an 4
75

array
Page

46 array_values() 4

[Ratnadip Sir : +91 702 079 5007]


Returns all the values of an array
array_walk()
47 3
Applies a user function to every member of an array
array_walk_recursive()
48 Applies a user function recursively to every member 5
of an array
arsort()
49 Sorts an array in reverse order and maintain index 3
association
asort()
50 3
Sorts an array and maintain index association
compact()
51 4
Create array containing variables and their values
count()
52 Counts elements in an array, or properties in an 3
object
current()
53 3
Returns the current element in an array
each()
54 Returns the current key and value pair from an 3
array
end()
55 Sets the internal pointer of an array to its last 3
element
extract()
56 Imports variables into the current symbol table 3
from an array
in_array()
57 4
Checks if a specified value exists in an array
key()
58 3
Fetches a key from an array
76

krsort()
59 3
Page

Sorts an array by key in reverse order

[Ratnadip Sir : +91 702 079 5007]


ksort()
60 3
Sorts an array by key
list()
61 3
Assigns variables as if they were an array
natcasesort()
62 Sorts an array using a case insensitive "natural 4
order" algorithm
natsort()
63 4
Sorts an array using a "natural order" algorithm
next()
64 3
Advance the internal array pointer of an array
pos()
65 3
Alias of current()
prev()
66 3
Rewinds the internal array pointer
range()
67 3
Creates an array containing a range of elements
reset()
68 Sets the internal pointer of an array to its first 3
element
rsort()
69 3
Sorts an array in reverse order
shuffle()
70 3
Shuffles an array
sizeof()
71 3
Alias of count()
sort()
72 3
Sorts an array
uasort()
73 Sorts an array with a user-defined function and 3
maintain index association
77

uksort()
74 3
Page

Sorts an array by keys using a user-defined function

[Ratnadip Sir : +91 702 079 5007]


usort()
75 Sorts an array by values using a user-defined 3
function

Array Sorting in PHP

Sorting is to arrange the elements of an array in a particular order. PHP


performs sorting on normal arrays like a numeric array and on
associative arrays. Normal arrays like numeric arrays can be sorted by
using the simple sort() function, and to perform the sorting on the
associative array, we have different functions.
The sorting can be done in ascending or descending order, alphabetical
or numerical order, natural way, random and also user-defined order.
For arrays like the numeric array or indexed array and for associative
arrays, sorting is done in ascending order or descending array based on
key or based on the value in any of the two orders like the ascending or
descending order. Sorting on arrays makes your search easier if the
data elements are in sorted form.
Syntax:
sort(array);

Sort in Alphabetical Order:


$people = array ('Rama', 'James', 'Mary', 'Alice',’ Radha’);

Sort in Numerical Order:


$ages = array (25,10,30,15,20);

Combining the above two arrays and creating one associative.


$people_ages = array ('James' => 25, 'Rama' => 10, 'Mary' =>
30, 'Alice' => 15, ‘Radha’ => 20);
78
Page

[Ratnadip Sir : +91 702 079 5007]


Sort in Numerical Order with Example:
<?php
//example to perform ages array
$ages = array(25,10,30,15,20);
//calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}
?>
Output:

79
Page

[Ratnadip Sir : +91 702 079 5007]


Sort in Alphabetical Order with Example:
<?php
//example to perform people array
$people= array('Rama', 'James', 'Mary', 'Alice', 'Radha');
// calculate length of array
$array_length = count($people);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($people);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i]."<br>";
}
?>
Output:

80
Page

[Ratnadip Sir : +91 702 079 5007]


Sorting an Associative Array
Performing sort on associative arrays which have key-value pair
association will end up in the lost of the keys. Also though the sort is
performed, each element of the array now has been assigned a new
numeric index.
// example to perform sort on people and ages array together
// you will find that the keys are not preserved and changed
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' =>
30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting we will use foreach loop
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach ($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Output:
81
Page

[Ratnadip Sir : +91 702 079 5007]


Types of Sorting in PHP
The different types of array functions are mentioned below, along with
the order of sort, whether it is in ascending or descending order and the
function sorts by either key or sorts by value are also mentioned.
1) sort(): this function sorts the input array in ascending order and
sorts it by value
2) rsort(): this function sorts the input array in descending order
and sorts it by value
3) asort(): this function sorts the input array in ascending order and
sorts it by value
4) arsort(): this function sorts the input array in descending order
and sorts by value
5) ksort(): this function sorts the input array in ascending order and
sorts it by key
6) krsort(): this function sorts the input array in descending order
and sorts it by key
7) usort(): this function sorts the input array based on the user-
defined function and sorts by value
8) uasort(): this function sorts the input array based on the user-
defined function and sorts by value
9) uksort(): this function sorts the input array based on the user-
defined function and sorts by key
10) natsort(): this function sorts the input array-based natural
ordering.
11) natcasesort(): this function sorts the input array-based natural
ordering and is case insensitive.
12) shuffle(): this function sorts the input array based on the value,
and the output is a random order of values.
82
Page

[Ratnadip Sir : +91 702 079 5007]


1) sort()
This function we have already seen. This function performs sorting on
the given array and arranges the elements of the array in ascending
array.
Code:
//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}
Output:

83
Page

[Ratnadip Sir : +91 702 079 5007]


2) rsoft()
This function performs sorting on the given array and arranges the
elements of the array in descending array, opposite of what sort()
function does. Also, the sorting is performed with values.
Example 1 : Code:
//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
rsort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}
Output:

84
Page

[Ratnadip Sir : +91 702 079 5007]


Example 2 : Code:
//example to perform people array
$people= array('Rama', 'James', 'Mary', 'Alice', 'Radha');
// calculate length of array
$array_length = count($people);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i] ."<br>";
}
echo '<hr>';
//performing sort
rsort($people);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i]."<br>";
}
Output:

85
Page

[Ratnadip Sir : +91 702 079 5007]


3) asort()
This function performs sorting on the given array and arranges the
array’s values in ascending order, opposite of what sort() function does.
Also, the sorting is performed with values and not keys.
Code:
//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' =>
30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
asort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Output:
86
Page

[Ratnadip Sir : +91 702 079 5007]


4) arsort()
This function performs sorting on the given array and arranges the
array’s values in a descending array. This example prints the array
using a foreach loop and outputs the result as before sorting and after
sorting.
Code:
//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' =>
30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
arsort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
`echo $key."=>".$value."<br>";
}
Output: 87
Page

[Ratnadip Sir : +91 702 079 5007]


5) ksort()
This function performs sorting on the given array and arranges the keys
of the array in ascending order. This example prints the array using a
foreach loop and outputs the result as before sorting and after sorting.
Code:
//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' =>
30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
ksort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Output:
88
Page

[Ratnadip Sir : +91 702 079 5007]


6) krsort()
This function performs sorting on the given array and arranges the keys
of the array in descending order.
This example prints the array using a foreach loop and outputs the
result as before sorting and after sorting.
Code:
//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' =>
30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
krsort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Output:
89
Page

[Ratnadip Sir : +91 702 079 5007]


7) natsort()
This function performs sorting on the given array and arranges the keys
of the array in descending order. This example prints the array using a
foreach loop and outputs the result as before sorting using assort()
function and after sorting using natsort() function.
This function refreshes the output as the function randomizes the order
of values in the given array. New numeric keys replace the keys
mentioned in the array are assigned. For example, 10 is greater than 7
in a human being view, but according to the sorting algorithm 10 comes
before 7.
We will use the natural flow of order.
Code:
<?php
$input = array("13 orange","14 Apple","15 3Banana","11
papaya","10 Grapes");;
$arr1 = $arr2 = $input;
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($arr1);
echo "Using asort function "."<br>";
//array before sorting
foreach($arr1 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
natsort($arr2);
90

echo "Using natsort function "."<br>";


foreach($arr2 as $key=>$value)
Page

[Ratnadip Sir : +91 702 079 5007]


{
echo $key."=>".$value."<br>";
}
?>
Output:

8) natcasesort()
This function works the same as natsort() but is case insensitive.
Code:
$input = array("13 orange","14 Apple","15 Banana","11
papaya","10 Grapes");;
$arr1 = $arr2 = $input;
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($arr1);
echo "Using asort function "."<br>";
91

//array before sorting


foreach($arr1 as $key=>$value)
Page

[Ratnadip Sir : +91 702 079 5007]


{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
natcasesort($arr2);
echo "Using natcasesort function "."<br>";
foreach($arr2 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Output:

92
Page

[Ratnadip Sir : +91 702 079 5007]


9) usort()
This function performs sorting on the given array and arranges the
values of the array in ascending order. This example prints the array
using for loop and outputs the result.
In this program, the usort function takes two parameters: the input
array and the other is the name of the function being called (here is
compare).
This compare function is user-defined; also, the function is optional.
This function returns 0 only if the condition in if block is satisfied, and
else it will send -1 if the values compared is smaller than the other and
1 if the values compared is greater than the other.
Code:
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
$numbers = array(10,4,5,3,20);
echo "Before Sort"."<br>";
//array after sorting
$array_length = count($numbers);
for($i=0;$i<$array_length;$i++)
{
echo $numbers[$i]."<br>";
}
echo '<hr>';
//performing sort
usort($numbers, "compare");
93

echo "After Sort"."<br>";


//array after sorting
Page

[Ratnadip Sir : +91 702 079 5007]


$array_length = count($numbers);
for($i=0;$i<$array_length;$i++)
{
echo $numbers[$i]."<br>";
}
Output:

10) uasort()
This function performs sorting on the given array and arranges the
array’s values in ascending order using the compare function.
Code:
<?php
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
echo '<hr>';
//performing sort
94

$input = array("num1"=>10,"num2"=>4,"num3"=>3,"num4"=>5,
Page

"num5"=>20);

[Ratnadip Sir : +91 702 079 5007]


uasort($input, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
?>
Output:

11) uksort()
This function performs sorting on the given array and arranges the
array’s keys in ascending order using the compare function.
Code:
<?php
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
95

}
Page

echo '<hr>';

[Ratnadip Sir : +91 702 079 5007]


//performing sort
$input = array("num1"=>10,"num2"=>4,"num3"=>3,"num4"=>5,
"num5"=>20);
uksort($input, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
?>
Output:

12) shuffle()
This function refreshes the output as the function randomizes the order
of values in the given array. New numeric keys replace the keys
mentioned in the array are assigned.
Code:
$input =
array('a'=>"Guava",'e'=>"Apple",'b'=>"Orange",'c'=>"Papaya",
'd' => "Banana");
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
96

echo $key."=>".$value."<br>";
}
Page

[Ratnadip Sir : +91 702 079 5007]


echo '<hr>';
shuffle($input);
echo 'You need to refresh to see the new shuffle
everytime'.'<br>';
$array_length = count($input);
echo '<hr>';
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Output:

97
Page

[Ratnadip Sir : +91 702 079 5007]


Reading Data in Web Pages & Handling Buttons
HTML Forms
An HTML form is a collection of HTML elements embedded within a
page. By adding different types of elements, you can create different
form fields, such as text fields, pull-down menus, checkboxes, and so on.
All Web forms start with an opening <form> tag, and end with a closing
</form> tag:
<form action="myscript.php" method="POST">
<!-- Contents of the form go here -->
</form>
Form attributes
There are two attributes within the opening <form> tag:
▪ action - tells the browser where to send the form data. This should
either be an absolute URL or a relative URL.
▪ method - tells the browser how to send the form data. You can use
two methods: GET is for sending small amounts of data and makes
it easy for the user to resubmit the form, and POST can send much
larger amounts of form data.
<form action="someform.php" method="post">
Name: <input type="text" name="Name" value="Jim" /><br />
Password: <input type="password" name="Password" /><br />
Age: <input type="text" name="Age" /><br />
<input type="submit" />
</form>
98
Page

[Ratnadip Sir : +91 702 079 5007]


PHP GET and POST
To read the data from a form, we can use the following three superglobal
variables.

Superglobal Array Description


Contains all the field names and values sent by
$_GET
a form using the get method
Contains all the field names and values sent by
$_POST
a form using the post method
Contains the values of both the $_GET and
$_REQUEST $_POST arrays combined, along with the values
of the $_COOKIE superglobal array
Each of these three superglobal arrays contains the field names from
the sent form as array keys, with the field values themselves as array
values.
<input type="text " name="emailAddress" value="" />
You could then access the value that the user entered into that form
field using either the $_GET or the $_REQUEST superglobal:
$email = $_GET["emailAddress"];
$email = $_REQUEST["emailAddress"];
Different between GET and POST
▪ GET sends its variables in the URL. It easy to see what was sent
with GET. And user can change what was sent There is usually a
low limit on the number of characters that can be sent in a URL.
If we try to send long variables using GET, we may lose some of
them.
▪ POST sends its variables behind the scenes and has a much higher
limit. It limit is usually several megabytes.
Browsers will not automatically resend post data if your user clicks the
Back button, you may get a message like "The data on this page needs
to be resent". This does not happen with GET, browsers will just resend
data as needed through URL.
99
Page

[Ratnadip Sir : +91 702 079 5007]


PHP has post_max_size entry in php.ini. It is usually set to 8M by
default, which is 8 megabytes.
Example:
index.html
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>PHP</title>
</head>

<body>
<form action="index.php" method="post">
<label for="firstName">First name</label>
<input type="text" name="firstName" id="firstName"
value="" /><br><br>

<label for="lastName">Last name</label>


<input type="text" name="lastName" id="lastName"
value="" /><br><br>

<label for="password1">Choose a password</label>


<input type="password" name="password1" id="password1"
value="" /><br><br>
<label for="password2">Retype password</label>
<input type="password" name="password2" id="password2"
value="" /><br><br>

<label for="genderMale">Are you male...</label>


<input type="radio" name="gender" id="genderMale"
value="M" />
100

<label for="genderFemale">...or female?</label>


<input type="radio" name="gender" id="genderFemale"
value="F" /><br><br>
Page

[Ratnadip Sir : +91 702 079 5007]


<label for="favoriteWidget">What's your favorite
widget?</label>
<select name="favoriteWidget" id="favoriteWidget"
size="1">
<option value="superWidget">The
SuperWidget</option>
<option value="megaWidget">The MegaWidget</option>
<option value="wonderWidget">The
WonderWidget</option>
</select><br><br>

<label for="newsletter">Do you want to receive our


newsletter?</label>
<input type="checkbox" name="newsletter"
id="newsletter" value="yes" /><br><br>

<label for="comments">Any comments?</label>


<textarea name="comments" id="comments" rows="4"
cols="50"> </textarea><br><br>
<div style="clear: both;"><br>
<input type="submit" name="submitButton"
id="submitButton" value="Send Details" />
<input type="reset" name="resetButton"
id="resetButton" value="Reset Form" style="margin-right:
20px;" />
</div>
</form>
</body>
</body>

</html>
101
Page

[Ratnadip Sir : +91 702 079 5007]


index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>Thank you for registering. Here is the information you
submitted:</p>
<dl>
<dt>First name</dt><dd><?php echo
$_POST["firstName"]?></dd>
<dt>Last name</dt><dd><?php echo
$_POST["lastName"]?></dd>
<dt>Password</dt><dd><?php echo
$_POST["password1"]?></dd>
<dt>Retyped password</dt><dd><?php echo
$_POST["password2"]?></dd>
<dt>Gender</dt><dd><?php echo $_POST["gender"]?></dd>
<dt>Favorite widget</dt><dd><?php echo
$_POST["favoriteWidget"]?></dd>
<dt>Do you want to receive our newsletter?</dt><dd><?php
echo $_POST["newsletter"]?></dd>
<dt>Comments</dt><dd><?php echo
$_POST["comments"]?></dd>
</dl>

</body>
</html>
102
Page

[Ratnadip Sir : +91 702 079 5007]


Output 1:

Output 2:

103
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Form TextField
A text input field allows the user to enter a single line of text.
Value attribute
You can optionally prefill the field with an initial value using the value
attribute. To leave it blank, specify an empty string for the value
attribute, or leave the attribute out altogether.
<label for="textField">A text input field</label>
<input type="text" name="textField" id="textField" value="" />
Example 1:
index.html
<html>
<body>
<form action="index.php" method="get">
<input type="text" name="user" />
<input type="submit" value="hit it!" />
</form>
</body>
</html>
index.php
<?php
print "Welcome <b>" . $_GET ['user'] . "</b><br/>";
?>

104
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Form Textarea
A text area field is similar to a text input field, but it allows the user to
enter multiple lines of text.
Unlike most other controls, an initial value is placed between the
<textarea> ... </textarea> tags, rather than in a value attribute.
A textarea element must include attributes for the height of the control
in rows (rows) and the width of the control in columns (cols):
Example
index.html
<html>
<body>
<form action="index.php" method="get">
<textarea name="address" rows="5" cols="40"></textarea>
<input type="submit" value="hit it!" />
</form>
</body>
</html>
index.php
<?php
print "Your address is: <br/><b>" . $_GET ['address'] .
"</b>";
?>

105
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Form CheckBox
A checkbox field is a simple toggle button. It can be either on or off.
The value attribute should contain the value that will be sent to the
server when the checkbox is selected. If the checkbox isn't selected,
nothing is sent.
<label for="checkboxField">A checkbox field</label>
<input type="checkbox" name="checkboxField" id="checkboxField"
value="yes" />
You can preselect a checkbox by adding the attribute
checked="checked" to the input tag:
<input type="checkbox" checked="checked" ... />.
By creating multiple checkbox fields with the same name attribute, you
can allow the user to select multiple values for the same field.
Example
index.html
<html>
<body>
<form action ="index.php">

<ul>
<li><input type ="checkbox" name ="chkFries" value
="11.00">Fries</li>
<li><input type ="checkbox" name ="chkSoda" value
="12.85">Soda</li>
<li><input type ="checkbox" name ="chkShake" value
="1.30">Shake</li>
<li><input type ="checkbox" name ="chkKetchup" value
=".05">Ketchup</li>
</ul>
<input type ="submit">
</form>
106

</body>
</html>
Page

[Ratnadip Sir : +91 702 079 5007]


index.php
<?php
print "chkFries:" . $chkFries . "<br/>";
print "chkSoda:" $chkSoda . "<br/>";
print "chkShake:" . $chkShake . "<br/>";
print "chkKetchup" . $chkKetchup . "<br/>";

$total = 0;

if (!empty($chkFries)){
print ("You chose Fries <br>");
$total = $total + $chkFries;
}

if (!empty($chkSoda)){
print ("You chose Soda <br>");
$total = $total + $chkSoda;
}

if (!empty($chkShake)){
print ("You chose Shake <br>");
$total = $total + $chkShake;
}

if (!empty($chkKetchup)){
print ("You chose Ketchup <br>");
$total = $total + $chkKetchup;
}

print "The total cost is \$$total";

?>
107
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Form Select
Form Select as Pull-down menu
A pull-down menu allows users to choose a single item from a
predefined list of options. The size attribute's value of 1 tells the
browser that you want the list to be in a pull-down menu format.
Within the select element, you create an option element for each of your
options.
Place the option label between the <option> ... </option> tags.
Each option element can have an optional value attribute, which is the
value sent to the server if that option is selected.
If you don't include a value attribute, the text between the <option> ...
</option> tags is sent instead:
<label for="pullDownMenu">A pull-down menu</label>
<select name="pullDownMenu" id="pullDownMenu" size="1">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

Form Select as List Box


A list box works like a pull-down menu, except that it displays several
options at once.
To turn a pull-down menu into a list box, change the size attribute from
1 to the number of options to display at once:
<label for="listBox">A list box</label>
<select name="listBox" id="listBox" size="3">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
108
Page

[Ratnadip Sir : +91 702 079 5007]


Form Select as multi-select list box
A multi-select list box allows the user to select multiple items at once
by holding down Ctrl or Command key.
To turn a normal list box into a multi-select box, add the attribute
multiple with a value of "multiple" to the select element.
If the user selects more than one option, all the selected values are sent
to the server:
<label for="multiListBox">A multi-select list box</label>
<select name="multiListBox" id="multiListBox" size="3"
multiple="multiple">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
You can preselect an option in any type of select element by adding the
attribute selected="selected" to the relevant <option> tag - for example:
<option value="option1" selected="selected">.
Example:
index.html
<html>
<body>
<div>
<form action="index.php" method="post">
<p><select name="products[]" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select></p>
<p><input type="submit" value="hit it!" /></p>
</form>
</div>
109

</body>
</html>
Page

[Ratnadip Sir : +91 702 079 5007]


index.php
<?php/*from ww w . j ava 2 s . c o m*/
if(is_array ( $_POST ['products'] )) {
print "<p>Your product choices are:</p>";
print "<ul>";
foreach ( $_POST ['products'] as $value ) {
print "<li>$value</li>\n";
}
print "</ul>";
}
?>

PHP Form RadioButton

The radio buttons are for single choice from multiple options. All radio
buttons in the group have the same name attribute.

Only one button can be selected per group. As with checkboxes, use the
value attribute to store the value that is sent to the server if the button
is selected.

The value attribute is mandatory for checkboxes and radio buttons, and
optional for other field types.
<label for="radioButtonField1">A radio button field</label>
<input type="radio" name="radioButtonField"
id="radioButtonField1" value="radio1" />
<label for="radioButtonField2">Another radio button</label>
<input type="radio" name="radioButtonField"
id="radioButtonField2" value="radio2" />
Example:
index.html
<html>
<body>
<form action="index.php" method="post">
<b>Please select your favorite color wine:</b> <br>
110

<input type="radio" name="color" value="white"> White


<input type="radio" name="color" value="rose"> Rose
Page

<input type="radio" name="color" value="red"> Red <br>

[Ratnadip Sir : +91 702 079 5007]


<input type="submit" value="Submit This Form">
</form>
</body>
</html>
index.php
<?php
$color = $_POST['color'];
if( ( $color != null ) )
{
$msg .= "a nice $color ";
echo( $msg );
}
?>

PHP Form Hidden Field


A hidden field is not displayed on the page.
It simply stores the text value specified in the value attribute.
Hidden fields are great for passing additional information from the
form to the server.
<label for="hiddenField">A hidden field</label>
<input type="hidden" name="hiddenField" id="hiddenField"
value="" />
Example:
<?php//from w w w . j av a2s .c om
$num_to_guess = 42;
$message = "";
if (! isset ( $_POST ['guess'] )) {
$message = "Welcome!";
} else if ($_POST ['guess'] > $num_to_guess) {
$message = $_POST ['guess'] . " is too big!";
} else if ($_POST ['guess'] < $num_to_guess) {
$message = $_POST ['guess'] . " is too small!";
} else {
111

$message = "Well done!";


}
Page

$guess = ( int ) $_POST ['guess'];

[Ratnadip Sir : +91 702 079 5007]


$num_tries = ( int ) $_POST ['num_tries'];
$num_tries ++;
?>
<html>
<body>
<?php print $message?>
Guess number: <?php print $num_tries?><br />
<form method="post" action="<?php
print $_SERVER ['PHP_SELF']?>">
<input type="hidden" name="num_tries"
value="<?php
print $num_tries?>" /> Type your guess here: <input
type="text" name="guess" value="<?php
print $guess?>" />
</form>
</body>
</html>

PHP Form File Upload


A file select field allows the users to choose a file on their hard drive for
uploading to the server. The value attribute is usually ignored by the
browser:
<label for="fileSelectField">A file select field</label>
<input type="file" name="fileSelectField" id="fileSelectField"
value="" />

Information

PHP creates a superglobal array called $_FILES containing various


pieces of information about the file or files.

Each file is described by an element in the $_FILES array keyed on the


name of the field that was used to upload the file.

For example, say your form contained a file select field called photo:
<input type="file" name="photo" value="" />
112
Page

[Ratnadip Sir : +91 702 079 5007]


PHP Redirect after a Form Submission

Redirection is done by outputting a Location using PHP using the


header() function.

Here's how to redirect to a page called thanks.html:

header( "Location: thanks.html" );

Don't output any content to the browser via echo() or print(), or by


including HTML markup outside the <?php ... ?> tags before calling
header().

Example

Here's a quick example of a form handler script that redirects to a thank


- you page:
<?php //from ww w .j a va2 s .c om
if ( isset( $_POST["submitButton"] ) ) {
// (deal with the submitted fields here)
header( "Location: thanks.html" );
exit;
} else {
displayForm();
}
function displayForm() {
?>
<!DOCTYPE html5>
<html>
<body>
<form action="index.php" method="post">
<label for="firstName">First name</label>
<input type="text" name="firstName" id="firstName"
value="" />
<label for="lastName">Last name</label>
<input type="text" name="lastName" id="lastName"
value="" />
113

<input type="submit" name="submitButton"


id="submitButton" value= "Send Details" />
</form>
Page

[Ratnadip Sir : +91 702 079 5007]


</body>
</html>
<?php
}
?>

Q. Write a Program to calculate Factorial of a Number by using Text


areas labels and command buttons.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>PHP</title>
</head>
<body>
<form action="" method="post">
Enter the Number : <br>
<input type="number" name="number" id="number">
<input type="submit" name="submit" value="Submit">
</form>

<?php
if($_POST){
$fact = 1;
// Getting Value form Input Text Box 'number'
$number = $_POST['number'];
echo "Factorial of $number : <br><br>";
// Start Loop
for($i = 1; $i <= $number; $i++){
$fact = $fact * $i;
}
echo $fact ."<br>";
}
?>
114

</body>
</html>
Page

[Ratnadip Sir : +91 702 079 5007]

You might also like