Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

Introduction to PHP

PHP is one of the most widely used server side scripting language for web development. Popular
websites like Facebook, Yahoo, Wikipedia etc, and even our college website are developed using
PHP.

What is PHP?
PHP stands for Hypertext Pre-Processor. PHP is a scripting language used to develop static and
dynamic webpages and web applications. Here are a few important things you must know about PHP:
1. PHP is an Interpreted language, hence it doesn't need a compiler.
2. To run and execute PHP code, we need a Web server on which PHP must be installed.
3. PHP is a server side scripting language, which means that PHP is executed on the server and the
result is sent to the browser in plain HTML.
4. PHP is open source and free.

Is PHP the right language?


If you are still confused about whether you should learn PHP or is PHP the right language for your
web project, then here we have listed down some of the features and usecases of PHP language, which
will help you understand how simple yet powerful PHP scripting language is and why you should
learn it.
1. PHP is open source and free, hence you can freely download, install and start developing using it.
2. PHP has a very simple and easy to understand syntax, hence the learning curve is smaller as
compared to other scripting languages like JSP, ASP etc.
3. PHP is cross platform, hence you can easily develop and move/deploy your PHP code/project to
almost all the major operating systems like Windows, Linux, Mac OSX etc.
4. All the popular web hosting services support PHP. Also the web hosting plans for PHP are
generally the amongst the cheapest plans becasue of its popularity.
5. Popular Content Management Systems like Joomla, Drupal etc are developed in PHP and if you
want to start your own website like Matrusri, you can easily do that with PHP.
6. With PHP, you can create static and dynamic webpages, perform file handling operations, send
emails, access and modify browser cookies, and almost everything else that you might want to
implement in your web project.
7. PHP is fast as compared to other scripting languages like JSP and ASP.
8. PHP has in-built support for MySQL, which is one of the most widely used Database management
system.
These are some of the main features of PHP, while as you will learn the language you will realise that
apart from these features,

Uses of PHP
To further fortify your trust in PHP, here are a few applications of this amazing scripting language:
1. It can be used to create Web applications like Social Networks(Facebook, Digg),
Blogs(Wordpress, Joomla), eCommerce websites(OpenCart, Magento etc.) etc.
2. Comman Line Scripting. You can write PHP scripts to perform different operations on any
machine, all you need is a PHP parser for this.
3. Create Facebook applications and easily integrate Facebook plugins in your website, using
Facebook's PHP SDK. Check this link for more information.
4. Sending Emails or building email applications because PHP provides with a robust email sending
function.
5. Wordpress is one of the most used blogging(CMS) platform in the World, and if you know PHP,
you can try a hand in Wordpress plugin development.

Install PHP on your Local Machine


To run PHP scripts on any machine(server, computer etc) we need PHP installed on it. In this
tutorial, we will learn how to install PHP on our computer/laptop and setup the development
environment.

Requirements for PHP


To run PHP scripts, we need the following services:
1. PHP Parser: To execute PHP scripts, PHP installation is required.
2. Web Server: Because PHP is mostly used to develop websites, hence most of its
implementations comes bundled with Apache Web Server, which is required to host the
application developed in PHP over HTTP.
3. Database: Any one database management system, which is generally MySQL, as PHP
comes with a native support for MySQL
Now, you can install all the 3 services separately yourself, or you can simply download and install
softwares which automatically installs all the above services.
The most popular such software package is XAMPP.
What is XAMPP?
XAMPP stands for:
X: Cross Platform, as it supports all the moder operating systems like Windows, Mac OSX, Linux
etc.
A: Apache Web Server
M: MySQL database management system.
P: PHP installation
P: Perl scripting language

You can easily download and install XAMPP from this link. The installation process is simple and
once installed you will see a small window like this, showing the status of various services which
are running.

You can easily control, stop and restart, various services using the XAMPP Control Panel.
Upon successful installation, a folder with name xampp will be created in the C drive(by default).
In the folder xampp there are many sub-folders like apache, cgi-bin, FileZillaFTP etc, but the
most important sub-folders are:
1. htdocs: This is the folder in which we will keep all our PHP files.
2. mysql: This folder contains all the files for the MySQL database. By default the MySQL
databse runs on port number 3306.
3. php: This folder holds all the installation files for PHP. All the configurations for the current
PHP installation is saved in php.ini file which is stored in this folder.
If everything seems fine and the apache server is running(check in the XAMPP control panel),
open your Web browser and enter localhost in the address bar and hit enter. You will see the
default page of Apache web server.
Other Software Packages
XAMPP is not the only available package, although it is the most widely used one. Here are a
few other Operating System specific options that you can download and install:
 WAMP: It's for Windows (Window, Apache, MySQL and PHP)
 MAMP: It's for Mac OSX (Macintosh, Apache, MySQL and PHP)
 LAMP: It's for Linux (Linux, Apache, MySQL and PHP)

IDE or Editor for writing PHP code


As PHP code is not compiled, you can even use a simple editor like Notepad to create PHP code
files. But it's always good to have a nice looking Editor which can highlight the code, provide you
suggestions while coding, and even analyze your code for syntax errors as your write it.
Before we checkout the list of IDEs and Editors, we must know the difference between both.
An Editoris a simple text editor with enhanced capabilities like syntax highlighting etc, many
modern editors also allows for language specific plugin download to support more features.
Whereas, an IDE is an integrated development environment, which is a self-contained package
that allow you to write, compile, execute and debug code in the same place.
So if you want a light weight software, go for any Editor, and if you want a heavy weight IDE, you
can choose any one from the list below.
So here are a few good IDEs and Editors:
1. Netbeans IDE
2. Eclipse IDE
3. PyStorm IDE
4. Atom Editor
5. Brackets Editor
6. Notepad ++
7. Sublime Text
Download and install anyone you want. I personally use Atom Editor, as it is lightening fast,
comes with some amazing themes options and plugins.

First PHP Example


In this tutorial we will learn what is the syntax to write basic PHP code, how we can integrate
PHP code in an HTML file and how to run the PHP script and check the output in the browser.

Hello World script in PHP


All the php code is written inside php code tags which is <?php and ?>. And the file with php code
is saved with an extension .php. Here is a simple example:
<?php
// code statements
?>
Hence a simple Hello, World! program in PHP will be:
<?php
echo "Hello, World!";
?>

Hello, World!
echo is a command used in PHP to display anything on screen.
If we want to include this php code in an HTML document, we can do so like this:
<!DOCTYPE>
<html>
<body>
<?php
echo "<h1>Hello, World!</h1>";
?>
</body>
</html>
Now copy the above code and paste it in you Code Editor or IDE and save the file with the
name hello_world.php
Now go to your C directory where XAMPP was installed, and open xampp → htdocs and create
a new folder with name Matrusri and put your php code file hello_world.php in the Matrusri
folder.
Now visit the following link in your browser: localhost/ Matrusri /hello_world.php and you
would see Hello, World! written on the screen. Notice that Hello, World! is written as a heading
because in the HTML code we specified that Hello, World! should be printed as a heading as put
it inside the heading tag <h1>
PHP Syntax Rules
Below we have a listed down the main syntax rules that you must follow while writing php code.
1. All the php code in a php script should be enclosed within <?php and ?>, else it will not be
considered as php code. Adding php code inside the PHP tags is known as Escaping to
php.
<?php ... ?>

Apart from the standard <?php and ?>, you can also use the Short-open tags:
<? ... ?>

Or use the HTML script tags, like we do for adding javascript code in HTML document:
<script language="PHP"> ... </script>

2. Every expression in PHP ends with a semicolon ;


3. Commenting PHP code: Both single line and multi-line comments are supported in PHP. For
single line comment, we can either use # or // before the comment line. For example,
4. <?php
5. # This is also a single line comment
6. # another line of comment
7.
8. // This is a single line comment
9. echo "Example for Single line Comments";
?>

And for multi-line comments, we use /* ... */. For example,


<?php
/*
This is also a single line comment
another line of comment
*/
echo "Example for Multi-line Comments";
?>

10. PHP is case sensitive, which means that a variable $tiger is not same as $Tiger. Both of
these, represent two different variables here.
But all the predefined keywords and functions like if, else, echo etc are case insensitive.
<?php
echo "Hello, World!";
ECHO "Hello, World!";
?>

Hello, World!

Hello, World!

11. PHP uses curly braces to define a code block.


12. <?php
13. if($zero == 0)
14. {
15. echo "If condition satisfied";
16. echo "This is a code block";
17. }
?>

Don't worry we will learn about if...else conditions in details, this is just to demonstrate the
use of curly braces.

Variables in PHP 5
When we want to store any information(data) on our computer/laptop, we store it in the
computer's memory space. Instead of remembering the complex address of that memory space
where we have stored our data, our operating system provides us with an option to create
folders, name them, so that it becomes easier for us to find it and access it.
Similarly, in any programming/scripting language, when we want to use some data value in our
program/script, we can store it in a memory space and name the memory space so that it
becomes easier to access it. The name given to the memory space is called a Variable.
In PHP, a variable is declared using a $ sign, followed by the variable name.
Syntax:
<?php
$variableName = value;
?>

Creating a Variable
In the example below we have create a different types of variables:
<?php
$str = "I am a string";
$int = 4;
$float = 3.14;
// You can name your variable anything
$wow = "Wow!";
?>
In PHP, you don't have to declare the variable first and then use it, like it's done in Java, C++ etc,
but in PHP the variable is created at the moment you assign it a value, like Python.
Also, in PHP we do not have to specify the type of data that we will be storing in a variable. You
can create a variable and save any type of data in it. Hence PHP is quite loosely typed
language.

Rules for creating Variables in PHP


Here we have a few basic rules that you must keep in mind while creating variables in PHP. All
the rules are explained with help of simple examples.
1. A variable name will always start with a $ sign, followed by the variable name.
2. A variable name should not start with a numeric value. It can either start with an alphabet or
an underscore sign _.
3. <?php
4. $var = "I am a variable";
5. $_var = 5;
6. // Invalid variable name
7. $7var = "I am a variable too";
?>

8. A variable name can only contain alphabets, numbers and underscore symbol _.
9. Variable names in PHP are case-sensitive, which means $love is not same as $Love.
10. <?php
11. $car = "Jaguar E-Pace";
12. echo "My favorite car is $car";
13. // below statement will give error
14. echo "I love $Car";
?>

My favorite car is Jaguar E-Pace

Notice: Undefined variable: Car

PHP echo and print functions


In this tutorial we will learn about two of the most important methods of PHP which are not built-in
functions of PHP language, but they are language constructs.
<?php
echo "Hello, I am a language construct";
?>
You must be wondering, What is a language construct? A language construct is
accepted/executed by the PHP parser as it is, in other words th PHP parser doesn't have to
parse and modify a language construct to execute it, as it is ready for execution by default.
Hence, language constructs are faster than any built-in functions.

PHP Echo
echo() function is used to print or output one or more strings. We have specifically
mentioned string here because, the syntax of the echo function is:
echo(string)
Although you can use echo() function to output anything, as PHP parser will automaticallly
convert it into string type.
echo doesn't need parenthesis, although you can use parenthesis if you want.
<?php
echo "I am open";
echo ("I am enclosed in parenthesis");
?>

I am open
I am enclosed in parenthesis

Printing a basic sentence


We have already covered it multiple times, still:
<?php
echo "I am a sentence";
?>

I am a sentence
Printing multiple strings using comma ,
Here is how you can use multiple strings as parameters for echo.
<?php
echo 'This','is','a','broken','sentence';
?>

This is a broken sentence


Printing a multiline text(string)
<?php
echo "This is a
multiline sentence
example";
?>

This is a multiline sentence example


Printing a string variable
<?php
$str = "I am a string variable";
echo $str;
?>

I am a string variable
Printing a string variable with some text
Below we have explained how using double quotes and single quotes leads to different output
when we use a string variable with some plain text in echo.
<?php
$weird = "Stupid";
echo "I am $weird";
echo 'I am $weird';
?>

I am Stupid
I am $weird
As you can see, when we use double quotes the value of the string variable gets printed, while
if we use single quotes, the variable is printed as it is.
Escaping special characters
As seen in previous examples, a double quote is required by echo to confirm what has to be
printed. But what if you want to print the double quotes too? In such cases, we use an escape
sequence to escape special characters from their special meanings. In PHP, a backslash \ is
used to escape special characters.
Below we have a simple example:
<?php
echo "Hello, this is a \"beautiful\" picture";
?>

Hello, this is a "beautiful" picture


As you can see, the double quotes are printed in the output.

PHP Print
The PHP print is exactly the same as echo, with same syntax and same usage. Just
replace echowith print in all the above examples, and they will work just fine.

Data Types in PHP 5


PHP Data types specify the different types of data that are supported in PHP language. There are total
8 data types supported in PHP, which are categorized into 3 main types. They are:
1. Scalar Types: boolean, integer, float and string.
2. Compound Types: array and object.
3. Special Types: resource and NULL.

PHP Boolean
A boolean data type can have two possible values, either True or False.
$a = true;
$b = false;

PHP Integer
An Integer data type is used to store any non-decimal numeric value within the range -2,147,483,648
to 2,147,483,647.
An integer value can be negative or positive, but it cannot have a decimal.
$x = -2671;
$y = 7007;

PHP Float
Float data type is used to store any decimal numeric value.
A float(floating point) value can also be either negative or positive.
$a = -2671.01;
$b = 7007.70;

PHP String
String data type in PHP and in general, is a sequence of characters(or anything, it can be numbers and
special characters too) enclosed within quotes. You can use single or double quotes.
$str1 = "Hello";
$str2 = "What is your Roll No?";
$str3 = "4";

echo $str1;
echo "<br/>";
echo $str2;
echo "<br/>";
echo "Me: My Roll number is $str3";

Hello
What is your Roll No?
Me: My Roll number is 4

PHP NULL
NULL data type is a special data type which means nothing. It can only have one value, and that
is NULL.
If you create any variable and do not assign any value to it, it will automatically have NULL stored in it.
Also, we can use NULL value to empty any variable.
// holds a null value
$a;
$b = 7007.70;
// we can also assign null value
$b = null;

PHP 5 Constants
Constants are variables whose value cannot be changed. In other words, once you set a value
for a constant, you cannot change it.
In PHP, there are two ways to define a constant:
1. Using the define() method.
2. Using the const keyword.
Another very important point to remember is that while naming a constant, we don't have to
use $symbol with the constant's name.

Using define()
Below is the syntax for using the define() function to create a constant.
define(name, value, case-insensitive)
Parameters:
1. name: Name of the constant
2. value: Value of the constant
3. case-insensitive: Specifies whether the constant name is case sensitive or not. It's default
value is false, which means, by default, the constant name is case sensitive.
Time for an Example
Below we have a simple example where we have not mentioned the parameter case-
insensitive, hence it will automatically take the default value for that.
<?php
define(OMG, "Oh! my God.");
echo OMG;
?>

Oh! my God.
For the above constant definition, if we try to use the following statement we will get an error,
because the constant OMG is case sensitive.
<?php
define(OMG, "Oh! my God.");
echo omg;
?>

omg
echo will consider it as a string and will print it as it is, with a subtle NOTICE saying that the string
variable is not defined.
Now let's see another example where we will specify the case-insensitive parameter.
<?php
define(OMG, "Oh! my God.", true);
echo omg;
?>

Oh! my God.

Using the const Keyword


We can also define constants in PHP using the const keyword. But we can only use
the constkeyword to define scalar constants, i.e. only integers, floats, booleans and strings,
while define()can be used to define array and resource constants as well, although they are not
used oftenly.

Time for an Example


<?php
const OMG = "Oh! my God.";
echo OMG;
?>

Oh! my God.
When we define a constant using the const keyword, the constant name is always case sensitive.

PHP Operators
Operators are used to perform operations on PHP variables and simple values.
In PHP there are total 7 types of operators, they are:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Increment/Decrement Operators
5. Logical Operators
6. String Operators
7. Array Operators
There are a few additional operators as well like, Type operator, Bitwise operator, Execution
operators etc.
Based on how these operators are used, they are categorised into 3 categories:
1. Unary Operators: Works on a single operand(variable or value).
2. Binary Operators: Works on two operands(variables or values).
3. Ternary Operators: Works on three operands.

PHP Arithmetic Operators


These operators are used to perform basic arithmetic operations like addition, multiplication,
division, etc.
Name Operato What does it do? Example
r

Addition + It is used to perform normal addition. $a + $b

Subtraction - It is used to perform normal subtraction. $a - $b

Multiplication * It is used to perform multiplication. $a * $b

Division / It is used to perform division. $a / $b

Exponent ** It returns the first operand raised to the power the $a ** $b


second operand. $a ** $b = $a $b

Modulus(or, % It returns the remainder of first operand divided by $a % $b


Remainder) the second operand

PHP Assignment Operators


Assignment operators are used to assign values to variables, either as it is or after performing
some arithmetic operation on it. The most basic assignment operator is equal to=.
Operator Usage

= $a = $b, will save the value of variable $b to the variable $a

+- $a += $b is same as $a + $b
-= $a -= $b is same as $a - $b

*= $a *= $b is same as $a * $b

/= $a /= $b is same as $a / $b

%= $a %= $b is same as $a % $b

So basically, the assignment operator provides us with shorthand techniques to perform


arithmetic operations.

PHP Comparison Operators


As the name suggest, these are used to compare two values.
Name Operato What does it do? Example
r

Equal == It returns true if left operand is equal to the right $a == $b


operand.

Identical === It returns true if left operand is equal to the right $a === $b
operand and they are of the same type.

Not Equal != It returns true if left operand is not equal to the right $a != $b
operand.

Not Identical !== It returns true if left operand is not equal to the right $a !== $b
operand, and they are of different type as well.

Greater than > It returns true if left operand is greater than the right $a > $b
operand.

Less than < It returns true if left operand is less than the right $a < $b
operand.

Greater than or >= It returns true if left operand is greater than or equal $a >= $b
equal to to the right operand.

Less than or <= It returns true if left operand is less than or equal to $a <= $b
equal to the right operand.

PHP Increment/Decrement Operators


These operators are unary operators, i.e they require only one operand.
Operato Usage
r

++$a Pre Increment, It will first increment the operand by 1(add one to it) and then use it
or return it.

$a++ Post Increment, It will first return the operand and then increment the operand by 1.

--$b Pre Decrement, It will first decrement the operand by 1(subtract one from it) and
then use it or return it.

$b-- Post Decrement, It will first return the operand and then decrement the operand
by 1.
These operators are very useful and handy when use loops or when we have simply increment
any value by one in our program/script.

PHP Logical Operators


Logical operators are generally used when any action depends on two or more conditions.
Nam Operato What does it do? Example
e r

And and or && It returns true if both the operands(or expressions) returns true. $a && $b

Or or or || It returns true if any one out of the two operands(or $a || $b


expressions) returns true, or both return true.

Xor xor It returns true if any one out of the two operands(or $a xor $b
expressions) returns true, but not when both return true.

Not ! This is a unary operator. It returns true, if the operand(or !$a


expression) returns false.

PHP String Operators


String operators are used to perform operations on string. There are only two string operators,
generally PHP built-in functions are used to perform various operations on strings, we will learn
about them in coming tutorials.
Name Operato What does it do? Example
r

Concatenation . (a dot) It is used to concatenate(join together) two $a.$b


strings.

Concatenation .= It is used to append one string to another. $a .= $b


Assignment
Here we have a simple example to demonstrate the usage of both the string operators.
<?php
$a = "study";
$b = "tonight";
// concatenating $a and $b
echo $a.$b;

// appending $b to $a
$a .= $b
echo $a;
?>

matrusri
matrusri

PHP Array Operators


These operators are used to compare arrays.
Name Operato What does it do? Example
r

Equal == It returns true if both the arrays have same key/value $a == $b


pairs.

Identical === It returns true if both the arrays have same key/value $a === $b
pairs, in same order and of same type.

Not Equal != It returns true if both the arrays are not same. $a != $b

Not !== It returns true if both the arrays are not identical, based $a !== $b
Identical on type of value etc.

Union(Join) + It joins the arrays together $a + $b

PHP if, else and else


if Conditional Statements
While writing programs/scripts, there will be scenarios where you would want to execute a
particular statement only if some condition is satisfied. In such situations we use Conditional
statements.
In PHP, there are 4 different types of Conditional Statements.
1. if statements
2. if...else statements
3. if...elseif...else statements
4. switch statement
We will cover the switch statements in the next tutorial.

The if statement
When we want to execute some code when a condition is true, then we use if statement.
Syntax:
if(condition)
{
// code to be executed if 'condition' is true
}
Here is a simple example,
<?php

$age = 20;

if($age <= 25)


{
echo "You are not allowed to consume alchohol";
}
?>

The if...else statement


When we want to execute some code when a condition is true, and some other code when that
condition is false, then we use the if...else pair.
Syntax:
if(condition)
{
// code to be executed if 'condition' is true
}
else
{
// code to be executed if 'condition' is false
}
Here is a simple example,
<?php

$age = 26;

if($age <= 25)


{
echo "You are not allowed to consume alchohol";
}
else
{
echo "Enjoy the drinks";
}
?>

Enjoy the drinks

The if...else...elseif statement


When we want to execute different code for different set of conditions, and we have more than 2
possible conditions, then we use if...elseif...else pair.
Syntax:
if(condition1)
{
// code to be executed if 'condition1' is true
}
elseif(condition2)
{
// code to be executed if 'condition2' is true
}
else
{
/* code to be executed if both 'condition1'
and 'condition2' are false */
}
Here is a simple example,
<?php
// speed in kmph
$speed = 110;

if($speed < 60)


{
echo "Safe driving speed";
}
elseif($speed > 60 && $speed < 100)
{
echo "You are burning extra fuel";
}
else
{
// when speed is greater than 100
echo "Its dangerous";
}
?>

Its dangerous
In the example above, we have also used logical operator &&. Logical operators are very useful
while writing multiple conditions together.

PHP 5 Switch Statement


You must have used a lift which is used to go up and down a building, all you have to do is press
the button with the floor number where you want to go, or a TV remote, using which you can
change the channel on your TV just by selecting that channel number on the TV remote.

The switch statement


A switch statement is used to perform different actions, based on different conditions.
Using a switch statement, we can specify multiple conditions along with the code to be executed
when that condition is true, thereby implementing a menu style program.
Syntax:
switch(X)
{
case value1:
// execute this code when X=value1
break;
case value2:
// execute this code when X=value2
break;
case value3:
// execute this code when X=value3
break;
...
default:
/* execute this when X matches none of
of the specified options */
}

You can specify as many options as you want using a single switch code block.
X can be a variable or an expression.
In a switch statement, we provide the deciding factor which can be a variable or an expression to
our switch statement, and then we specify the different cases, each with a value, a piece of code
and a break statement.
break statement is specified to break the execution of the switch statement once the action
related to a specified value has been performed.
If we do not specify a break statement, then all the switch cases, after the matched case, will get
executed, until the next break statement.
The default statement is executed if no matching case is there.
<?php
$car = "Jaguar";

switch($car)
{
case "Audi":
echo "Audi is amazing";
break;
case "Mercedes":
echo "Mercedes is mindblowing";
break;
case "Jaguar":
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
?>

Jaguar is the best


PHP while and do...while Loop
As the name suggests, a Loop is used to execute something over and over again.
For example, if you want to display all the numbers from 1 to 1000, rather than
using echo statement 1000 times, or specifying all the numbers in a single echo statement with
newline character \n, we can just use a loop, which will run for 1000 times and every time it will
display a number, starting from 1, incrementing the number after each iteration or cycle.
In a Loop, we generally specify a condition or a LIMIT up till which the loop will execute, because
if we don't specify such a condition, how will we specify when the loop should end and not go on
for infinite time.

PHP while Loop


The while loop in PHP has two components, one is a condition and other is the code to be
executed. It executes the given code until the specified condition is true.
Syntax:
<?php
while(condition)
{
/*
execute this code till the
condition is true
*/
}
?>

For example, let's take the problem mentioned in the beginning of this tutorial. Let's print
numbers from 1 to 10.
<?php

$a = 1;

while($a <= 10)


{
echo "$a | ";
$a++; // incrementing value of a by 1
}
?>

PHP do...while Loop


The do...while loop is a little different from all the loops in PHP because it will execute at least
one time, even if the condition is false, can you guess how? Well because the condition is
checked after the loop's execution, hence the first time when the condition is checked, the loop
has already executed once.
Syntax:
<?php
do {
/*
execute this code till the
condition is true
*/
} while(condition)
?>

Let's implement the above example using do...while loop,


<?php

$a = 1;

do {
echo "$a | ";
$a++; // incrementing value of a by 1
} while($a <= 10)
?>

Let's take another example where even if the condition is false, still the loop will be executed
once.
<?php

$a = 11;

do {
echo $a;
$a++; // incrementing value of a by 1
} while($a <= 10)
?>

11
As we can see clearly, that the condition in the above do...while loop will return false because
value of variable $a is 11 and as per the condition the loop should be executed only if the value
of $a is less than or equal to 10.

PHP for and foreach Loop


In this tutorial we will learn about for and foreach loops which are also used to implement looping
in PHP.
To understand what are loops and how they work, we recommend you to go through the previous
tutorial.

PHP for Loop


The for loop in PHP doesn't work like while or do...while loop, in case of for loop, we have to
declare beforehand how many times we want the loop to run.
Syntax:
<?php
for(initialization; condition; increment/decrement)
{
/*
execute this code till the
condition is true
*/
}
?>
The parameters used have following meaning:
1. initialization: Here we initialize a variable with some value. This variable acts as the loop
counter.
2. condition: Here we define the condition which is checked after each iteration/cycle of the
loop. If the condition returns true, then only the loop is executed.
3. increment/decrement: Here we increment or decrement the loop counter as per the
requirements.
Time for an Example
Again, lets try to print numbers from 1 to 10, this time we will be using the for loop.
<?php

for($a = 1; $a <= 10; $a++)


{
echo "$a <br/>";
}
?>

1
2
3
4
5
6
7
8
9
10

Nested for Loops


We can also use a for loop inside another for loop. Here is a simple example of
nested for loops.
<?php

for($a = 0; $a <= 2; $a++)


{
for($b = 0; $b <= 2; $b++)
{
echo "$b $a ";
}
}

?>

0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2

PHP foreach Loop


The foreach loop in PHP is used to access key-value pairs of an array. This loop only works with
arrays and you do not have to initialise any loop counter or set any condition for exiting from the
loop, everything is done implicitly(internally) by the loop.
Syntax:
<?php
foreach($array as $var)
{
/*
execute this code for all the
array elements

$var will represent all the array


elements starting from first element,
one by one
*/
}
?>

Here is a simple example.


<?php

$array = array("Jaguar", "Audi", "Mercedes", "BMW");

foreach($array as $var)
{
echo "$var <br/>";
}

?>

Jaguar
Audi
Mercedes
BMW

PHP break statement


We have already seen and used break statements in the switch conditional statements.
To recall, in switch code blocks, we used break statement to break out of the switch block when a
valid case block gets executed.
Let's see an example for simple switch code:
<?php

$a = 1;

switch($a)
{
case 1:
echo "This is case 1";
break;
case 2:
echo "This is case 2";
break;
default:
echo "This is default case";
}

?>
This is case 1

But what if we forget to add the break statement at the end of each case block in the switchstatement?
In that case, the execution will still start from the matching case, but will not exit out of
the switch statement and will keep on executing every code statement below it until the
next breakstatement.
<?php

$a = 2;

switch($a)
{
case 1:
echo "This is case 1";
case 2:
echo "This is case 2";
default:
echo "This is default case";
}

?>

This is case 2
This is default case

Using break in Loops


In Loops, the break statement is very useful for situations when you want to exit out of the loop(stop
the loop), if some condition is satisfied.
Let's take a simple example of a for loop to understand how we can use break statement in loops.
In the example below, we want to find the first number divisible by 13, which is between 1762 and
1800, starting from 1762.
<?php

$x = 13;

for($i = 1762; $i < 1800; $i++)


{
if($i % $x == 0)
{
echo "The number is $i";
break;
}
}

?>

The number is 1768


In the above script, we start our for loop from 1762, and run it till 1800. In every iteration/cycle, we
check whether the incremented number is divisible by 13. When we find the first number for which
the remainder is 0, we exit from the loop using the break statement.
The usage of break statement is same for all the different types of loops.
PHP Functions
A Function is nothing but a 'block of statements' which generally performs a specific task and
can be used repeatedly in our program. This 'block of statements' is also given a name so that
whenever we want to use it in our program/script, we can call it by its name.
In PHP there are thousands of built-in functions which we can directly use in our program/script.
PHP also supports user defined functions, where we can define our own functions.
A function doesn't execute when its defined, it executed when it is called.

PHP User Defined Functions


Let's understand how we can define our own functions in our program and use those functions.
Syntax:
<?php

function function_name()
{
// function code statements
}

?>

Few Rules to name Functions


1. A function name can only contain alphabets, numbers and underscores. No other special
character is allowed.
2. The name should start with either an alphabet or an underscore. It should not start with a
number.
3. And last but not least, function names are not case-sensitive.
4. The opening curly brace { after the function name marks the start of the function code, and
the closing curly brace } marks the end of function code.

Time for an Example


Let's write a very simple function which will display a simple "Merry Christmas and a Very Happy
New Year" message. This script can actually be very useful when you have to send festive
emails to every friend of yours and you have to write the same message in all of them.
<?php
// defining the function
function greetings()
{
echo "Merry Christmas and a Very Happy New Year";
}

echo "Hey Martha <br/>";


// calling the function
greetings();
// next line
echo "<br/>";

echo "Hey Jon <br/>";


// calling the function again
greetings();

?>

Hey Martha
Merry Christmas and a Very Happy New Year
Hey Jon
Merry Christmas and a Very Happy New Year

Advantages of User-defined Functions


As we have already seen a simple example of using a function above, you must have understood
how time-saving it can be for large programs. Here are a few advantages of using functions for
you:
1. Reuseable Code: As it's clear from the example above, you write a function once and can
use it for a thousand times in your program.
2. Less Code Repetition: In the example above we just had one line of code in the function,
but what if we have 10 lines of code. So rather than repeating all those lines of code over and
over again, we can just create a function for them and simply call the function.
3. Easy to Understand: Using functions in your program, makes the code more readable and
easy to understand.

PHP Function Arguments


We can even pass data to a function, which can be used inside the function block. This is done
using arguments. An argument is nothing but a variable.
Arguments are specified after the function name, in parentheses, separated by comma. When we
define a function, we must define the number of arguments it will accept and only that much
arguments can be passed while calling the function.
Syntax:
<?php
/*
we can have as many arguments as we
want to have in a function
*/
function function_name(argument1, argument2)
{
// function code statements
}

?>
Let's take a simple example:
<?php
// defining the function with argument
function greetings($festival)
{
echo "Wish you a very Happy $festival";
}

echo "Hey Jai <br/>";


// calling the function
greetings("Diwali");

// next line
echo "<br/>";

echo "Hey Jon <br/>";


// calling the function again
greetings("New Year");

?>

Hey Jai
Wish you a very Happy Diwali
Hey Jon
Wish you a very Happy New Year
As you can see in the example above, how we changed our greetings() function to start taking
arguments, and now it can be used for sending greetings for different festivals.

PHP Default Function Arguments


Sometimes function arguments play an important role in the function code execution. In such
cases, if a user forgets to provide the argument while calling the function, it might lead to some
error.
To avoid such errors, we can provide a default value for the arguments which is used when no
value is provided for the argument when the function is called.
Let's take an example.
<?php

// defining the function with default argument


function greetings($festival = "Life")
{
echo "Wish you a very Happy $festival";
}

echo "Hey Jai <br/>";


// calling the function with an argument
greetings("Diwali");

// next line
echo "<br/>";

echo "Hey Jon <br/>";


// and without an argument
greetings();

?>
Hey Jai
Wish you a very Happy Diwali
Hey Jon
Wish you a very Happy Life
So when you forget to provide an argument while calling the function, to cover up, you can set
default values to the arguments to your functions.

PHP Function Returning Values


Yes, functions can even return results. When we have functions which are defined to perform
some mathematical operation etc, we would want to output the result of the operation, so we
return the result.
return statement is used to return any variable or value from a function in PHP.
Let's see an example.
<?php

function add($a, $b)


{
$sum = $a + $b;
// returning the result
return $sum;
}

echo "5 + 10 = " . add(5, 10) . "";

?>

5 + 10 = 15

PHP Function Overloading


Function overloading allows you to have multiple different variants of one function, differentiated
by the number and type of arguments they take.
For example, we defined the function add() which takes two arguments, and return the sum of
those two. What if we wish to provide support for adding 3 numbers.
To tackle such situations, what we can do is, we can define two different variants of the
function add(), one which takes in 2 arguments and another which accepts 3 arguments. This is
called Function Overloading.
Let's take an example,
<?php
// add function with 2 arguments
function add($a, $b)
{
$sum = $a + $b;
// returning the result
return $sum;
}

// overloaded add function with 3 arguments


function add($a, $b, $c)
{
$sum = $a + $b + $c;
// returning the result
return $sum;
}

// calling add with 2 arguments


echo "5 + 10 = " . add(5, 10) . "<br/>";

// calling add with 3 arguments


echo "5 + 10 + 15 = " .add(5, 10, 15) . "<br/>";
?>

5 + 10 = 15
5 + 10 + 15 = 30
Unfortunately, PHP does not support Function Overloading.
This was just to give you an idea about what function overloading is. In PHP, function signatures
are only based on their names and do not include the argument lists, hence we cannot have two
functions with same name.

PHP 5 Arrays
An array is used to store multiple values, generally of same type, in a single variable.
For example if you have a list of festivals that you want to store together, or may be a list of
stationary items, or list of colors, then you can either keep them in separate variables, but then
you will have to create a lot of variables and they won't be related to each other.
In such case, PHP arrays are used. Arrays can store multiple values together in a single variable
and we can traverse all the values stored in the array using the foreach loop.

Creating an Array
We can create an array in PHP using the array() function.
Syntax:
<?php
/*
this function takes multiple values
separated by comma as input to create
an aray
*/
array();
?>

In PHP there are 3 types of array:


1. Indexed Array: These are arrays with numeric index.
2. Associative Array: These are arrays which have a named key as index, the key can be
numeric or text.
3. Multidimensional Array: These are arrays which contain one or more arrays.

Time for an Example


Let's take a simple example for an array to help you understand how an array is created.
<?php
/*
a simple array with car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
?>

To access the data stored in an array, we can either use the index numbers or we can use
a foreachloop to traverse the array elements.
Index number for array elements starts from 0, i.e the first element is at the position 0, the second
element at position 1 and so on...
<?php
/*
a simple array with Lamborghini car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
// print the first car name
echo $lamborghinis[0];
echo "Urus is the latest Super SUV by Lamborghini";
?>

Urus
Urus is the latest Super SUV by Lamborghini

Advantages of Array
Here are a few advantages of using array in our program/script:
1. It's very easy to define simple list of related data, rather than creating multiple variables.
2. It's super easy to use and traverse using the foreach loop.
3. PHP provides built-in functions for sorting array, hence it can be used for sorting information
as well.

PHP Indexed Arrays


An indexed array is a simple array in which data elements are stored against numeric indexes.
All the array elements are represented by an index which is a numeric value starting from 0 for
the first array element.

Creating an Indexed Array


There are two different ways of creating an indexed array in PHP, they are,
Syntax for the 1st way to create indexed array:
<?php
/*
1st - direct array initialization
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
?>
and the syntax for the 2nd way to create indexed array is:
<?php
/*
2nd - distributed array initialization
*/
$suzuki[0] = "Swift";
$suzuki[1] = "Baleno";
$suzuki[2] = "Ertiga";
$suzuki[3] = "Brezza";
$suzuki[4] = "Vitara";
?>
No matter how we initialize the array, we can access the array as follows,
<?php
/*
Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki[0], "\n";
echo $suzuki[3], "\n";
echo $suzuki[2], "\n";
echo "Accessing the 1st array...";
echo $lamborghinis[1], "\n";
echo $lamborghinis[0], "\n";
echo $lamborghinis[2], "\n";
?>

Accessing the 2nd array...


Swift
Brezza
Ertiga
Accessing the 1st array...
Huracan
Urus
Aventador
Hence, to access an indexed array, we have to use the array name along with the index of the
element in square brackets.

Traversing PHP Indexed Array


Traversing an array means to iterate it starting from the first index till the last element of the
array.
We can traverse an indexed array either using a for loop or foreach. To know the syntax and
basic usage of for and foreach loop, you can refer to the PHP for and foreach loop tutorial.

Using for loop


While using the for loop to traverse an indexed array we must know the size/length of the array,
which can be found using the count() function.
Following is the syntax for traversing an array using the for loop.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// find size of the array
$size = count($lamborghinis);
// using the for loop
for($i = 0; $i < $size; $i++)
{
echo $lamborghinis[$i], "\n";
}
?>
Using the foreach loop
using foreach to traverse an indexed array is a better approach if you have to traverse the whole
array, as we do not have to bother about calculating the size of the array to loop around the
array.
Below we have used the foreach to traverse the $lamborghinis array.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// using the foreach loop
foreach($lamborghinis as $lambo)
{
echo $lambo. "\n";
}
?>

Advantages of Indexed Array


Here are a few advantages of using indexed array in our program/script:
1. Numeric index values make it easier to use and having numeric indexes are common to
almost all the programming languages, hence it also makes the code more readable for
others who go through your code.

PHP Associative Arrays


An associative array is similar to an indexed array, but rather than storing data sequentially with
numeric index, every value can be assigned with a user-designed key of string type.

Creating an Associative Array


Just like indexed array, there are two different ways of creating an associative array in PHP, they
are,
Syntax for the 1st way to create associative array:
<?php
/*
1st - direct array initialization
*/
$lamborghinis = array("suv"=>"Urus", "sports"=>"Huracan", "coupe"=>"Aventador");
?>
and the syntax for the 2nd way to create associative array is:
<?php
/*
2nd - distributed array initialization
*/
$suzuki["hatch"] = "Swift";
$suzuki["utility"] = "Ertiga";
$suzuki["suv"] = "Vitara";
?>
No matter how we initialize the array, we can access the array as follows,
<?php
/*
Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki["hatch"], "\n";
echo $suzuki["utility"], "\n";
echo $suzuki["suv"], "\n";
echo "Accessing the 1st array...";
echo $lamborghinis["suv"], "\n";
echo $lamborghinis["sports"], "\n";
echo $lamborghinis["coupe"], "\n";
?>

Accessing the 2nd array...


Swift
Ertiga
Vitara
Accessing the 1st array...
Urus
Huracan
Aventador
Hence, to access an associative array, we have to use the array name along with the index of the
element in square brackets, the only difference here is that the index will be a string not a
numeric value like in indexed array.

Traversing PHP Associative Array


Traversing an array means to iterate it starting from the first index till the last element of the
array.
We can traverse an associative array either using a for loop or foreach. To know the syntax and
basic usage of for and foreach loop, you can refer to the PHP for and foreach loop tutorial.

Using for loop


While using the for loop to traverse an associative array we must know the size/length of the
array, which can be found using the count() function.
Also, as the index in associative array is not numeric and not sequentially, hence to find the index
values or keys(as data saved in associative array is in the form of key-value), we can use the
function array_keys() to get an array of the keys used in the associative array.
Following is the syntax for traversing an array using the for loop.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// find size of the array
$size = count($lamborghinis);

// getting the array of keys/index strings


$keys = array_keys($lamborghinis);

// using the for loop


for($i = 0; $i < $size; $i++)
{
echo $lamborghinis[$keys[$i]] ." is a/an ". $keys[$i] ." car \n";
}
?>

Urus is a/an suv car


Huracan is a/an sports car
Aventador is a/an coupe car
Using the foreach loop
using foreach to traverse an associative array is a better approach if you have to traverse the
whole array, as we do not have to bother about calculating the size of the array to loop around
the array.
Below we have used the foreach to traverse the $lamborghinis array.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// using the foreach loop
foreach($lamborghinis as $key => $value)
{
echo $value ."is a/an ". $key ." car \n";
}
?>

Urus is a/an suv car


Huracan is a/an sports car
Aventador is a/an coupe car
Don't get confused by the syntax as $key=>$value, it means in every iteration of the foreach we
are representing the array as key-value pair.

Advantages of Associative Array


Here are a few advantages of using associative array in our program/script:
1. We can provide more meaningful key or index values to our array elements.
2. We can save more data, as we can have a string as key to the array element, where we can
have associated data to the value to be stored, like in our example, we stored the type of the
car as key along with the name of the car as value. Hence storing two different information in
one array element.

PHP Multidimensional Arrays


A multidimensional array is an array which stores another array at each index rather than
storing a single value. In simple words, a multidimensional array is an array of arrays.
In general practice, associative arrays are stored inside multidimensional arrays.

Creating a Multidimensional Array


As we have already seen how to create an associative array, and multidimensional array being
an array of arrays, will hold the associative arrays inside it.
Syntax for creating multidimensional array:
<?php
/*
multidimensional array initialization
*/
$cars = array(
array(
"name"=>"Urus",
"type"=>"SUV",
"brand"=>"Lamborghini"
),
array(
"name"=>"Cayenne",
"type"=>"SUV",
"brand"=>"Porsche"
),
array(
"name"=>"Bentayga",
"type"=>"SUV",
"brand"=>"Bentley"
),
);
?>
As we are dealing with array inside an array here, hence to access any information, we first need
to reach to that array, then get data from a particular array stored in the multidimensional array.
For example, if we want to display data for Urus car, then, first we have to get the first array
inside our multidimensional array, which can be accessed using index 0, and then inside that
array, we can display all the data, like we did in associative arrays.
<?php
/*
Accessing multidimensional array
*/
echo "Accessing multidimensional array...";
echo "Urus is an ".$cars[0]["type"]." manufactured by ".$cars[0]["brand"]."\n";
echo "Bentayga is an ".$cars[2]["type"]." manufactured by ".$cars[2]["brand"]."\n";
?>

Accessing multidimensional array...


Urus is an SUV manufactured by Lamborghini
Bentayga is an SUV manufactured by Bentley

Traversing PHP Multidimensional Array


Traversing an array means to iterate it starting from the first index till the last element of the
array.
We can traverse a multidimensional array either using two for loops or two foreach or
one forloop and one foreach. To know the syntax and basic usage of for and foreach loop, you
can refer to the PHP for and foreach loop tutorial.

Using one for loop and one foreach


In case of multidimensional array, we have to traverse the main array and then the arrays stored
inside the main arrays, hence we need two loops.
While using the for loop to traverse a multidimensional array we must know the size/length of the
array, which can be found using the count() function.
Let's take the array defined above for the first example of traversing multidimensional array.
<?php
/*
multidimensional array initialization
*/
$cars = array(
array(
"name"=>"Urus",
"type"=>"SUV",
"brand"=>"Lamborghini"
),
array(
"name"=>"Cayenne",
"type"=>"SUV",
"brand"=>"Porsche"
),
array(
"name"=>"Bentayga",
"type"=>"SUV",
"brand"=>"Bentley"
),
);

// array traversal
// find size of the array
$size = count($lamborghinis);

// using the for loop


for($i = 0; $i < $size; $i++)
{
foreach($cars[$i] as $key => $value) {
echo $key . " : " . $value . "\n";
}
echo "\n";
}

?>

name : Urus
type : SUV
brand : Lamborghini
name : Cayenne
type : SUV
brand : Prosche
name : Bentayga
type : SUV
brand : Bentley
In the above multidimensional array, we have the main array as indexed array and the arrays
stored as elements are associative.
Bu the main array can also be associative, let's take an example for it.
Also, as the index in associative array is not numeric and not sequentially, hence to find the index
values or keys(as data saved in associative array is in the form of key-value), we can use the
function array_keys() to get an array of the keys used in the associative array.
<?php
/*
multidimensional array initialization
*/
$cars = array(
"Urus" => array(
"type"=>"SUV",
"brand"=>"Lamborghini"
),
"Cayenne" => array(
"type"=>"SUV",
"brand"=>"Porsche"
),
"Bentayga" => array(
"type"=>"SUV",
"brand"=>"Bentley"
),
);

/*
array traversal
*/
// find size of the array
$size = count($lamborghinis);

// array keys
$keys = arra_keys($cars);

// using the for loop


for($i = 0; $i < $size; $i++)
{
echo $keys[$i]. "\n";
foreach($cars[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "\n";
}
echo "\n";
}

?>

Urus
type : SUV
brand : Lamborghini
Cayenne
type : SUV
brand : Prosche
Bentayga
type : SUV
brand : Bentley

Advantages of Multidimensional Array


Here are a few advantages of using multidimensional array in our program/script:
1. Detailed information can be stored in multidimensional array.
2. On top level, it can either be kept indexed or associative, which makes it more user-friendly,
as they can use it as per their requirements.

PHP Array Functions


We have covered basics of array, indexed arrays, associative arrays and multidimensional
arrays. Now let's dive deep into arrays and learn about the in-built functions for array processing
in PHP.
In general practice, using the right array function will save you a lot of time as they are pre-
defined in PHP libraries and all you have to do is call them to use them.

Commonly used PHP5 Array Functions


Below we have a list of some commonly used array functions in PHP:

sizeof($arr)
This function returns the size of the array or the number of data elements stored in the array.
It is just like count($arr) method, that we used in previous tutorials while traversing the array.
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");


echo "Size of the array is: ". sizeof($lamborghinis);

?>

Size of the array is: 3

is_array($arr)
To check whether the provided data is in form of an array, we can use the is_array() function. It
returns True if the variable is an array and returns False otherwise.
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// using ternary operator


echo is_array($lamborghinis) ? 'Array' : 'not an Array';

$mycar = "Urus";

// using ternary operator


echo is_array($mycar) ? 'Array' : 'not an Array';

?>

Array
not an Array

in_array($var, $arr)
When using an array, we may often want to check whether a certain value is present in the array
or not. For example, if get a list of certain cars, like we do in almost all our examples, to check if a
certain car is added into the array, we can use the in_array function.
Let's take an example and see,
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// new concept car by lamborghini


$concept = "estoque";

echo in_array($concept, $lamborghinis) ? 'Added to the Lineup' : 'Not yet!'


?>

Not yet!
As we can see unlike the other functions above, this one takes two arguments, one is the value
to be searched in the array, and the second one is the array itself.print_r($arr)
Although this is not an array function, but it deserves a special mention here, as we can use this
function to print the array in the most descriptive way possible. This function prints the complete
representation of the array, along with all the keys and values.
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");


print_r($lamborghinis);

?>

Array (
[0] => "Urus"
[1] => "Huracan"
[2] => "Aventador"
)

array_merge($arr1, $arr2)
If you want to combine two different arrays into a single array, you can do so using this function.
It doesn't matter whether the arrays to be combined are of same type(indexed, associative etc) or
different types, using this function we can combine them into one single array.
Let's take an example where we will merge an indexed array and an associative array.
<?php

$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
"Tata" => "Tigor"
);

// friends who own the above cars


$friends = array("Vinod", "Javed", "Navjot", "Samuel");

// let's merge the two arrays into one


$merged = array_merge($hatchbacks, $friends);

print_r($merged);

?>

Array (
[Suzuki] => Baleno
[Skoda] => Fabia
[Hyundai] => i20
[Tata] => Tigor
[0] => Vinod
[1] => Javed
[2] => Navjot
[3] => Samuel
)

array_values($arr)
In an array, data is stored in form of key-value pairs, where key can be numerical(in case of
indexed array) or user-defined strings(in case of associative array) and values.
If we want to take all the values from our array, without the keys, and store them in a separate
array, then we can use array_values() function.
Let's take the array $merged formed in the example above,
<?php

$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
"Tata" => "Tigor"
);

// friends who own the above cars


$friends = array("Vinod", "Javed", "Navjot", "Samuel");

// let's merge the two arrays into one


$merged = array_merge($hatchbacks, $friends);

//getting only the values


$merged = array_values($merged);

print_r($merged);

?>

Array (
[0] => Baleno
[1] => Fabia
[2] => i20
[3] => Tigor
[4] => Vinod
[5] => Javed
[6] => Navjot
[7] => Samuel
)

array_keys($arr)
Just like values, we can also extract just the keys from an array. Let's use this function to extract
the keys from the array $merged.
<?php

//getting only the keys


$keys = array_values($merged);

print_r($keys);

?>

Array (
[0] => Suzuki
[1] => Skoda
[2] => Hyundai
[3] => Tata
[4] => 0
[5] => 1
[6] => 2
[7] => 3
)

array_pop($arr)
This function removes the last element of the array. Hence it can be used to remove one element
from the end.
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// removing the last element


array_pop($lamborghinis);

print_r($lamborghinis);

?>

Array (
[0] => Urus
[1] => Huracan
)

array_push($arr, $val)
This function is the opposite of the array_pop() function. This can be used to add a new element
at the end of the array.
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador");

// adding a new element at the end


array_push($lamborghinis, "Estoque");

print_r($lamborghinis);

?>

Array (
[0] => Urus
[1] => Huracan
[2] => Aventador
[3] => Estoque
)

array_shift($arr)
This function can be used to remove/shift the first element out of the array. So, it is just
like array_pop() function but different in terms of the position of the element removed.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");

// removing the first element


array_shift($lamborghinis);

print_r($lamborghinis);

?>

Array (
[0] => Huracan
[1] => Aventador
)
Similar to this, we have another function array_unshift($arr, $val) to add a new value($val) at
the start of the array(as the first element).

sort($arr)
This function sorts the array elements in ascending order. In case of a string value array, values
are sorted in ascending alphabetical order.
Some other sorting functions are: asort(), arsort(), ksort(), krsort() and rsort().
<?php

$lamborghinis = array("Urus", "Huracan", "Aventador", "Estoque");

// sort the array


sort($lamborghinis);

print_r($lamborghinis);

?>

Array (
[0] => Aventador
[1] => Estoque
[2] => Huracan
[3] => Urus
)

array_map('function_name', $arr)
If you want to perform certain operation on all the values stored in an array, you can do it by
iterating over the array using a for loop or foreach and performing the required operation on all
the values of the array.
Or, you can use the function array_map(). All we have to do is define a separate function to which
we will provide the values stored in the array one by one(one at a time) and it will perform the
operation on the values. Let's have an example,
<?php

function addOne($val) {
// adding 1 to input value
return ($val + 1);
}
$numbers = array(10, 20, 30, 40, 50);

// using array_map to operate on all the values stored in array


$numbers = array_map('addOne', $numbers);

print_r($numbers)

?>
Array (
[0] => 11
[1] => 21
[2] => 31
[3] => 41
[4] => 51
)
The function array_walk($arr, 'function_name') works just like the array_map() function.

array_flip($arr)
This function interchange the keys and the values of a PHP associative array.
<?php

$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
"Tata" => "Tigor"
);

// we can directly print the result of array flipping


print_r(array_flip($hatchbacks));

?>
Array (
[Baleno] => Suzuki
[Fabia] => Skoda
[i20] => Hyundai
[Tigor] => Tata
)

array_reverse($arr)
This function is used to reverse the order of elements, making the first element last and last
element first, and similarly rearranging other array elements.
<?php

$num = array(10, 20, 30, 40, 50);


// printing the array after reversing it
print_r(array_reverse($num));

?>

Array (
[0] => 50
[1] => 40
[2] => 30
[3] => 20
[4] => 10
)

array_rand($arr)
If you want to pick random data element from an array, you can use the array_rand() function.
This function randomly selects one element from the given array and returns it.
In case of indexed array, it will return the index of the element, in case of associative array, it will
return the key of the selected random element.
<?php

$colors = array("red", "black", "blue", "green", "white", "yellow");

echo "Color of the day: ". $colors[array_rand($colors)];

?>

Color of the day: green


Every time you run the above script, it will return a random color value from the array.

array_slice($arr, $offset, $length)


This function is used to create a subset of any array. Using this function, we define the starting
point($offset, which is the array index from where the subset starts) and the length(or, the
number of elements required in the subset, starting from the offset).
Let's take an example,
<?php

$colors = array("red", "black", "blue", "green", "white", "yellow");

print_r(array_slice($colors, 2, 3));

?>

Array (
[0] => blue
[1] => green
[2] => white
)

PHP 5 Strings
Just like any other programming language, Strings in Php are also a collection of alphanumeric
characters, enclosed in single quotes for simple string data and double quotes for complex string data.

Creating PHP 5 Strings


There are many different ways in which we can create a string in Php. Let's start with the most
simplest way,
<?php

$srt1 = "This is a String";


$str2 = 'This is also a String';

?>
We can define a string using double quotes as well as single quotes.
But, what if the string has a single or double quote in it, then what?
<?php

$srt1 = "This is "a" String";


$str2 = 'This is also 'a' String';

?>
Both the above string definitions will result in error, as we cannot include a double quote in the string,
if the string is defined inside double quotes.
But it will work, if the string contains double quotes, but it is defined using single quotes and vice
versa, for example,
<?php

// string inside double quotes, with a single quote


$srt1 = "This is 'a' String";

// string inside single quotes, with a double quote


$str2 = 'This is also "a" String';

?>
There is one more simple technique to deal with the quotes problem, it is known as Escaping Special
Character, which can be done using a backslash.
Let's take an example,
<?php

// escaping double quote using backslash


$srt1 = "I\"ll handle this.";

// escaping single quote using backslash


$str2 = 'I\'ll handle this.';

echo $str1;
echo "\n"; // new line
echo $str2;

?>

I"ll handle this.


I'll handle this.
As evident from the examples above, it's quite simple to declare and define a string variable in PHP 5.
Just be careful of the quotes and a few other special characters like $. Let's take an example
for $special character too.
<?php

// string with $
$srt1 = "pas$word";

echo $str1;

?>

NOTICE : Undefined variable


pas
Running the above code, will show that only the part of the string before the $ symbol will get stored
in the variable, while $word is treated as a variable, which is not assigned any value, hence, PHP prints
a NOTICE. Now let's try to use backslash to escape it,
<?php

// string with escaped $


$srt1 = "pas\$word";

echo $str1;

?>

pas$word

Creating String using Heredoc method


If we want to define a multiline string, using the here doc syntax is the best and the easiest technique.
Using this methodology we can create strings with more than one line, without string concatenation.
Also, there is no requirement of escaping double or single quotes, if we use the here docmethodology
to define strings.
Let's take an example:
<?php

$str = <<< EOT


Take a right from the T point,
and the go straight to fins the "Shop"
EOT;

echo $str;

?>

Take a right from the T point, and the go straight to fins the "Shop"
Here EOT is just a synonymn for end of text, which means nothing. These 3 characters are just to
mark the start and end of the multiline string.
You can use EOF or maybe SQL if you use this to define your multiline SQL query, like,
<?php

$tablename = "products";

$str = <<< SQL


Select * from $tablename
Where product_name = "widgets"
SQL;

echo $str;

?>

Select * from products Where product_name = "widgets"

Creating String using Nowdoc method


The Nowdoc method of creating a string is similar to the Heredoc method, with only one difference,
which is that the string is not parsed, hence if we want to add a value to our string using some other
variable`, like we did in the SQL query string above, we cannot do that with Nowdoc.
Let's take an exmple,
<?php

$hername = "Selena";

$str = <<< 'LOV'


This is my declaration of love,
for $hername
LOV;

echo $str;

?>

This is my declaration of love, for $hername


The variable in the string is not translated into its value.

Printing the String variable


Printing a string variable is simple, let's take 2 examples, in the first we will only print the string
variable using the echo method, and in the second, we will append a string variable with some other
text in the echo method, enclosed in single and double quotes.
<?php

$hername = "Selena";

// only the string variable


echo $hername;

// for new line


echo "\n";

// string variable with text and single quote


echo '$hername, hello!';

echo "\n";

// string variable with text and double quote


echo "$hername, hello!";

?>

Selena
$hername, hello!
Selena, hello!
See the difference, single quotes does not parse the text inside it, hence the variable is not translated
into its value, while in case of double quotes, it is.

PHP 5 String Functions


We have covered what are strings and how to create them in the last tutorial, now let's dive deep
into strings and learn about the in-built functions for string processing in PHP.
In general practice, using the right string function will save you a lot of time as they are pre-
defined in PHP libraries and all you have to do is call them to use them.

Commonly used PHP 5 String Functions


Below we have a list of some commonly used string functions in PHP:

strlen($str)
This function returns the length of the string or the number of characters in the string including
whitespaces.
<?php

$str = "Welcome to Matrusri";

// using strlen in echo method


echo "Length of the string is: ". strlen($str);

?>

Length of the string is: 23

str_word_count($str)
This function returns the number of words in the string. This function comes in handly in form
field validation for some simple validations.
<?php

$str = "Welcome to Matrusri";

// using str_word_count in echo method


echo "Number of words in the string are: ". str_word_count($str);

?>

Number of words in the string are: 3

strrev($str)
This function is used to reverse a string.
Let's take an example and see,
<?php

$str = "Welcome to Matrusri";

// using strrev in echo method


echo "Reverse: ". strrev($str);

?>

Reverse: thginotydutS ot emocleW

strpos($str, $text)
This function is used to find the position of any text/word in a given string. Just like an array,
string also assign index value to the characters stored in it, starting from zero.
<?php

$str = "Welcome to Matrusri";

// using strpos in echo method


echo "Position of 'Matrusri' in string: ". strpos($str, 'Matrusri');

?>

Position of 'Matrusri' in string: 11

str_replace($replacethis, $replacewith, $str)


This function is used to replace a part of the string with some text. While using this function, the
first argument is the part of string that you want to replace, second argument is the new text you
want to include, and the last argument is the string variable itself.
Let's take an example,
<?php

$str = str_replace("Matrusri", "Matrusri.com", "Welcome to Matrusri");

echo $str;

?>

Welcome to Matrusri.com

ucwords($str)
This function is used for formatting the string. This function converts first letter/character of every
word in the string to uppercase.
Let's take an example and see,
<?php

$str = "welcome to matrusri";

echo ucwords($str);

?>

Welcome To Matrusri

strtoupper($str)
To convert every letter/character of every word of the string to uppercase, one can
use strtoupper()method.
<?php

$str = "welcome to matrusri";

echo strtoupper($str);

?>
WELCOME TO MATRUSRI

strtolower($str)
This function is used to convert every letter/character of a string to lowercase.
<?php

$str = "WELCOME TO matrusri";

echo strtolower($str);

?>

welcome to matrusri

str_repeat($str, $counter)
This function is used to repeat a string a given number of times. The first argument is the string
and the second argument is the number of times the string should be repeated.
<?php

$str = "Matrusri";

echo str_repeat($str, 4);

?>

MatrusriMatrusriMatrusriMatrusri

strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done alphabetically. If the first
string is greater than second string, the result will be greater than 0, if the first string is equal to
the second string, the result will be equal to 0 and if the second string is greater than the first
string, then the result will be less than 0.
<?php

$str1 = "Matrusri";
$str2 = "Matrusri.com";

// comparing str1 and str2


echo strcmp($str1, $str2);

// comparing str2 and str1


echo strcmp($str2, $str1);

// comparing str1 with str1


echo strcmp($str1, $str1);

?>

-4
4
0
substr($str, $start, $length)
This function is used to take out a part of the string(substring), starting from a particular position,
of a particular length.
The first argument is the string itself, second argument is the starting index of the substring to be
exracted and the third argument is the length of the substring to be extracted.
<?php

$str = "Welcome to Matrusri";

echo substr($str, 11, 12);

?>

Matrusri

trim($str, charlist)
This function is used to remove extra whitespaces from beginning and the end of a string. The
second argument charlist is optional. We can provide a list of character, just like a string, as the
second argument, to trim/remove those characters from the main string.
<?php

$str1 = " Hello World ";

echo trim($str1) . "<br/>";

$str2 = "Hello Hello";

echo trim($str2,"Heo");

?>

Hello World
llo Hell
As you can see in the output, additional spaces from the beginning and end are removed and in
the second case, the characters specified are removed from the beginning and the end of the
string.

explode(separator, $str, $limit)


This function is used to break a string, create an array of the broken parts of the string and return
the array. The first argument, separator defines where to break the string from. It can be a
space, hiphen(-) or any other character.
The second argument of this function is the string itself and the third argument is the limit, which
specifies the number of array elements to return. the third argument is optional.
Let's have an example,
<?php

$str = "Its a beautiful day";

// we can directly print the result of explode


print_r(explode(" ", $str));
?>
Array (
[0] => Its
[1] => a
[2] => beautiful
[3] => day
)
In the example above, we have provided space as separator to break the string and return an
array.
If we provide the third argument limit as well, we can limit the number of array elements
returned. For example, if we provide 2 as the third argument, then we will only get 2 elements in
the array, the first two.

implode(separator, $arr)
This function is used to form a string using the array elements from the array provided and join
them using the separator.
Let's take an example,
<?php

$arr = array("Its", "a", "beautiful", "day");

// <br> is used to jump to next line


echo implode(" ", $arr) . "<br>";
echo implode("-", $arr) . "<br>";
echo implode("/", $arr) . "<br>";

?>

Its a beautiful day


Its-a-beautiful-day
Its/a/beautiful/day

nl2br($str)
This function is used to change line break or \n to the HTML tag for line break, which is <br>.
This function is very useful to format string data to display on HTML pages because when a
multiline form data is submitted, it has \n included in the strnig for line breaks, but when you
display it on your HTML page, the line breaks will not get rendered because HTML doesn't
understand \n.
<?php

echo nl2br("Its a\nbeautiful day");

?>

Its a
beautiful day

PHP 5 Form Handling


When we develop a website or a web application, we often have to create forms to take input
from users, like a Login form or a Registration form.
Creating a form on the webpage is accomplished using HTML, while PHP serves as a transport
for those values from the webpage to the server and then in further processing those values.
PHP provides two superglobals $_GET and $_POST for collecting form-data for processing.

Understanding How HTML Form Works


Let's create a simple HTML form and try to understand how it works, what are the different
attributes available in the <form> tag and what are they used for.
<html>
<body>

<form action="form-handler.php" method="POST">


Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
<input type="submit">
</form>

</body>
</html>
In the code above, we have used the <form> tag to create an HTML form, with input fields for
Name and Email along with submit button to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are for?
1. action: Using this attribute, we can specify the name of the file which will collect and handle
the form-data. In the example above, we have provided name of a Php file.
2. method: This attribute specify the means of sending the form-data, whether it will be submitted
via POST method or GET method.
Below we have the same form with method as GET,
<html>
<body>

<form action="form-handler.php" method="GET">


Name: <input type="text" name="name"> <br/>
Email: <input type="text" name="email"> <br/>
<input type="submit">
</form>

</body>
</html>

PHP Form Handling with POST


If we specify the form method to be POST, then the form-data is sent to the server using the
HTTP POST method.
Below, we have the code, to access the form-data in the Php file specified in the action attribute
of our HTML form.
<?php

// getting the value of name field


$name = $_POST["name"];
// getting the value of the email field
$email = $_POST["email"];

echo "Hi, ". $name . "<br>";


echo "Your email address: ". $email ."<br>";

?>

Hi, Matrusri
Your email address: we@matrusri.com
You will get the above output, if you provide name as "Matrusri" and email address as
"we@matrusri.com".

PHP Form Handling with GET


If we specify the form method to be GET, then the form-data is sent to the server using the HTTP
GET method.
Below, we have the code, to access the form-data in the Php file specified in the action attribute
of our HTML form, this time using the GET superglobal.
<?php

// getting the value of name field


$name = $_GET["name"];
// getting the value of the email field
$email = $_GET["email"];

echo "Hi, ". $name . "<br>";


echo "Your email address: ". $email ."<br>";

?>

Hi, Matrusri
Your email address: we@matrusri.com
Again, the output remains the same.
The first step to process the form-data is to fetch the data using POST or GET superglobals,
once you have the data, you can do anything with it, display it on your webpage, save the data
into database, perform validations etc.

GET vs. POST: When to use What!


Now, you must be wondering, which one should we use. Well, both GET and POST are used for
the same purpose but they work differently.
When a user submits a form, the values from the input fields are stored in an array,
like array(key1=>value1, key2=>value2,...) and then passed on to the destination(Php file)
specified in the action attribute of the <form> tag.
Using GET method
In case of GET method, form-data is submitted as URL parameters, i.e. all the values entered in
the form fields by the user are sent to the action script, appended in the URL.
Let's take a simple example to understand, below we have a simple HTML form,
<html>
<body>

<form action="form-handler.php" method="GET">


Name: <input type="text" name="name"> <br/>
Age: <input type="text" name="age"> <br/>
<input type="submit">
</form>

</body>
</html>
We have two input fields in above form, one is name and the other one is age. When we click on
submit, we will be redicrected to the following URL, form-handler.php?name=Matrusri&age=5,
with the form-data appended to the URL.
Sending the form-data as URL parameters proves out useful at times as you can
easily bookmark links with form-data, but for appending parameters in a URL there is a limit
of 2000 characters, hence for forms with large number of fields, it is not suggested, as some
data might get lost or the form submission may lead to error.
The Php file form-handler.php will look like,
<?php

// name attribute of the input field goes inside the


// square brackets of $_GET superglobal
$name = $_GET["name"];
$age = $_GET["age"];

echo "Your name is ". $name . " and you are ". $age . " years old".

?>

Your name is Matrusri and you are 5 years old


As the form-data is visible to everyone because it sent as URL parameters, hence we should not
use GET method for a form with sensitive data, like passwords etc.

Using POST method


When we use the POST method, the array of key-value pair(the form-data), coming from the
HTML form are sent as part of the HTTP request, hence they are invisible to the user.
Also, there is no character limit for the information/data being transmitted.
POST method also supports multipart form-data upload which is used for file upload.
We would recommend, that you use the POST method while working on any PHP web
application/project.
Let's take a simple example to understand, below we have a simple HTML form,
<html>
<body>

<form action="form-handler.php" method="POST">


Name: <input type="text" name="name"> <br/>
Age: <input type="text" name="age"> <br/>
<input type="submit">
</form>

</body>
</html>
The Php file form-handler.php will look like,
<?php

// name attribute of the input field goes inside the


// square brackets of $_POST superglobal
$name = $_POST["name"];
$age = $_POST["age"];

echo "Your name is ". $name . " and you are ". $age . " years old".

?>

Your name is Matrusri and you are 5 years old

The HTML Form


We will be creating an HTML form with 2 text fields for name and email, 1 textarea for the user to
provide a self-description(more like about me) and a radio button set for asking the user's
gender.
Below we have the HTML code for the form.
<html>
<body>

<form action="form-handler.php" method="POST">

Name: <input type="text" name="name"> <br/>


Email: <input type="text" name="email"> <br/>

About Me:<br/>
<textarea name="aboutme"></textarea> <br/>

Gender:
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="male"> Male
<br/>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>
The PHP Code
In the above form we are asking the user for 4 different inputs, let's see how we can fetch the
submitted values for the fields in PHP.
<?php

// getting the value of name field


$name = $_POST["name"];
// getting the value of the email field
$email = $_POST["email"];
// getting the value of the aboutme field
$aboutme = $_POST["aboutme"];
// getting the value of the radio buttons
$gender = $_POST["gender"];

?>
Easy, right? Yes, to access the form-data for different types of HTML form elements, all you need
is $_POST.
But an HTML form is a great entry point for hackers to play around by entering script or some
malicious code into the input fields to cause some error/issue in your PHP script.
To tackle with it, it's good to put some validations in the PHP code for validating the user inputs
submitted in the form-data.

PHP Form Validation


Now we will learn some basic validations that can be easily applied to the submitted form-data to
validate it before performing any action on it.
<?php

// getting the value of name field


$name = $_POST["name"];
// check if name is empty or not
if(empty($name)) {
echo "Name is required";
}

?>
In the code above we are checking whether the user has entered name value in the form or not,
similarly you can put a check on all the mandatory form fields.
To validate email address, there is a special function available in PHP which we can use to
validate email addresses. The function is filter_var($email, FILTER_VALIDATE_EMAIL), let's see
how it works.
<?php
// getting the value of the email field
$email = $_POST["email"];

// checking if the email value is valid


if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Email value invalid";
}

?>
The filter_var() function returns true for a valid email address and returns false for an invalid
email address.
Validating a form in PHP depends on your requirements too. For example, if you don't have any
mandatory fields in your form, then you don't have to worry about checking whether the
submitted values are empty or not.
If you have email address field, we suggest you validate it.
You can even add more validations like checking the input for malicious codes like <script> tags
using regular expressions.

What is $_SERVER["PHP_SELF"]?
Sometimes we can avoid having an extra PHP file to handle/process the form-data and can
include the PHP code in the file with the HTML form itself.
In such scenarios, we will have to submit the form to the same webpage again, and we can
use $_SERVER["PHP_SELF"] as the form action.
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
What this superglobal does is that it returns the filename of the current webpage, which then acts
as the action script.
But as this returns the existing filename from the URL, you must be a little careful because users
may inject some unwanted code from the URL, so to avoid it, we can use
the htmlspecialchars() function to convert any special character in the string(URL in this case)
into HTML entities.
So you should use,
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">

State Management in PHP 5


HTTP is a stateless protocol which means every user request is processed independently and it
has nothing to do with the requests processed before it. Hence there is no way to store or send
any user specific details using HTTP protocol.
But in modern applications, user accounts are created and user specific information is shown to
different users, for which we need to have knowledge about who the user(or what he/she wants
to see etc) is on every webpage.
PHP provides for two different techniques for state management of your web application, they
are:
1. Server Side State Management
2. Client Side Server Management

Server Side State Management


In server side state management we store user specific information required to identify the user
on the server. And this information is available on every webpage.
In PHP we have Sessions for server side state management. PHP session variable is used to
store user session information like username, userid etc and the same can be retrieved by
accessing the session variable on any webpage of the web application until the session variable
is destroyed.

Client Side State Management


In client side state management the user specific information is stored at the client side i.e. in the
bowser. Again, this information is available on all the webpages of the web application.
In PHP we have Cookies for client side state management. Cookies are saved in the browser
with some data and expiry date(till when the cookie is valid).
One drawback of using cookie for state management is the user can easily access the cookie
stored in their browser and can even delete it.

Cookies in PHP 5
Cookie is a small piece of information stored as a file in the user's browser by the web server.
Once created, cookie is sent to the web server as header information with every HTTP request.
You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.
Before we move on to how to create, update and delete a cookies, let's learn a few realworld use
of cookies.

Realworld Use of Cookies


1. To store user information like when he/she visited, what pages were visited on the website
etc, so that next time the user visits your website you can provide a better user experience.
2. To store basic website specific information to know this is not the first visit of user.
3. You can use cookies to store number of visits or view counter.
I hope this gives you an idea about how you can utilize cookies in your web application.

Types of Cookies
There are two types of cookies, they are:
1. Session Cookie: This type of cookies are temporary and are expire as soon as the session
ends or the browser is closed.
2. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time.
Then the cookie will only expire after the given expiration time, until then it will be a valid
cookie.

Creating a Cookie in PHP


In PHP we can create/set a cookie using the setcookie() function.
Below we have the syntax for the function,
setcookie(name, value, expire, path, domain, secure)
The first argument which defines the name of the cookie is mandatory, rest all are optional
arguments. Let's understand what are the available arguments that we can supply to
the setcookie() function to set a cookie.
Argumen What is it for?
t

name Used to specify the name of the cookie. It is a mandatory argument. Name of the
cookie must be a string.

value Used to store any value in the cookie. It is generally saved as a pair with name. For
example, name is userid and value is 7007, the userid for any user.

expire Used to set the expiration time for a cookie. if you do not provide any value, the
cookie will be treated as a session cookie and will expire when the browser is
closed.

path Used to set a web URL in the cookie. If set, the cookie will be accessible only from
that URL. To make a cookie accessible through a domain, set '/' as cookie path.

domain The domain of your web application. It can be used to limit access of cookie for
sub-domains. For example, if you set the domain value as wwww.matrusri.com,
then the cookie will be inaccessible from blog.matrusri.com

secure If you set this to 1, then the cookie will be available and sent only over HTTPS
connection.
So if we want to create a cookie to store the name of the user who visited your website, and set
an expiration time of a week, then we can do it like this,
<?php

setcookie("username", "iamabhishek", time()+60*60*24*7);

?>
To access a stored cookie we use the $_COOKIE global variable, and can use the isset() methos
to check whether the cookie is set or not.
Let's have a complete example where we will set a cookie and then retrieve it to show its value in
the HTML page.
<?php
// set the cookie
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
<html>
<body>

<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>

</body>
</html>
So by providing the name of the cookie inside the square brakets with the global
variable $_COOKIE[]we can access the cookie.
NOTE: setcookie() function should be placed before the starting HTML tag(<html>).

Updating Cookie in PHP


To update/modify a cookie, simply set it again. For example, if we want to update the username
stored in the cookie created above, we can do it using setcookie() method again,
<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time()+60*60*24*7);
?>
<html>
<body>

<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>

</body>
</html>
We just update the value of username cookie from iamabhishek to iamNOTabhishek.

Delete a Cookie in PHP


To delete/remove a cookie, we need to expire the cookie, which can be done by updating the
cookie using the setcookie() function with expiration date in past.
<?php
// updating the cookie
setcookie("username", "iamNOTabhishek", time() - 3600);
?>
<html>
<body>

<?php
echo "cookie username is deleted!";

?>

</body>
</html>
And with this, we now know how to create a cookie, how to update it and how to delete it when
we no longer need it. Next up, Sessions!

Sessions in PHP 5
To store information accessible accross web pages, we use sessions. Session is not stored on
the user browser like cookie, hence it is a more secure option.
As we know HTTP is a stateless protocol, if a user visits a webpage and perform some action,
there is no way to remember what he did when the user navigates to the next webpage.
Let's take a practical example, when you log into your facebook account, by providing your email
address and password, until and unless you logout, the web application remembers who you are
and display what your friends are posting and liking on your News Feed, you can update your
profile, send someone message, join a group etc, this is accomplished by Session.
When a user logs into their account on any web application, a session is created for them, and in
the session their username or userid or some other unique identifier is stored, which is then used
on the consecutive webpages to show information specific to that user. On logout, the session is
destroyed.
Session is not limited by any size limit, you can store any information in the session, irrespective
of its size.
Before we move on to how to start, update and end a session in PHP, let's learn a few realworld
use of session.

Realworld Use of Session


1. Web applications which require a user to login, use session to store user information, so that
on every webpage related information can be displayed to the user.
2. In eCommerce websotes, shopping cart is geberally saved as part of session.
I hope this gives you an idea about how you can utilize session in your web application.

Start a Session in PHP


In PHP we can start a session by using the session_start() function. And data is stored in the
session using session variable, which can be assigned different values using global
variable $_SESSION
In simpler words, using the function session_start() we initialize the session, in which we can
store information using the session variable $_SESSION.
Let's take an example, below we have a webpage with Php file named first_page.php
<?php
// start the session
session_start();

// set the session variable


$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>

<html>
<body>

<?php
echo "Session variable is set.";
?>

<a href="second_page.php">Go to Second Page</a>

</body>
</html>
NOTE: The function session_start() should be the first statement of the page, before any HTML
tag.

Getting PHP Session Variable Values


In the code above, we have started a session and set two session variables. Above webpage will
also have a link to navigate to Second page second_page.php.
Below is the code for second_page.php, in which we fetch values from the session variable
which are set in the first_page.php.
<?php
// start the session
session_start();

// get the session variable values


$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>

<html>
<body>

<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>

</body>
</html>

Username is: iamabhishek


User id is: 1
You must be thinking, why we used session_start() here although we did not set any new
values in the session variable.
session_start() function is used to initialize a new session and to fetch the ongoing session(if
already started), and then, using the $_SESSION global variable, we can either set new values into
the session or get the saved values.
If there are too many values stored in the session, and you don't know which one do you want to
get, you can use the below code to print all the current session variable data.
<?php
// start the session
session_start();
?>

<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

Array (
[username] => iamabhishek,
[userid] => 1
)

Update Session Variable in PHP


To update any value stored in the session variable, start the session by
calling session_start()function and then simply overwrite the vakue to update session variable.
<?php
// start the session
session_start();

// update the session variable values


$_SESSION["userid"] = "1111";
?>

<html>
<body>

<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>

</body>
</html>

Username is: iamabhishek


User id is: 1111
We just updated the value of userid in the session variable from 1 to 1111.

Destroy a Session in PHP


To clean the session variable or to remove all the stored values from the session variable we can
use the function session_unset() and to detroy the session, we use session_destroy() function.
<?php
// start the session
session_start();
?>

<html>
<body>
<?php
// clean the session variable
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>
We use these functions on pages like logout or checkout in case of an eCommerce website to
clean the session variable off the user specific data and to eventually destroy the current session.

File Handling in PHP 5


When we develop a web application using PHP, quite often we need to work with external files,
like reading data from a file or maybe writing user data into file etc. So it's important to know how
files are handled while working on any web application.

File Handling Operations


File handling starts with creating a file, reading its content, writing into a file to appending data
into an existing file and finally closing the file. Php provides pre-defined functions for all these
operations, so let's start by knowing these functions.
1. Create a File: fopen()
2. Open a File: fopen()
3. Read a File: fread()
4. Write to a File: fwrite()
5. Append to a File: fwrite()
6. Close a File: fclose()
7. Delete a File: unlink()
You must be wondering that why we have specified same functions for multiple file operations,
well, that is because just by changing one or more arguments, same function can be used to
perform multiple operations on file.
Uses of File in Applications
Following are some of the practical use cases where we need files in our web applications.
 Oftenly data is stored in for of JSON files, amd Php code has to read the file and then display
the data on web page.
 In some simple applications, no database is used, rather data is stored in files.
 In some web applications, you may have to prepare a file for user to download, in that case
Php code will create a file, write data in it and then allow the user to download it.
The above usecases are just to show that very oftenly file handling is required.

Create, Open and Close a File in PHP 5


To create a new file or to open an existing file, we use the fopen() function provided by PHP and
to close a file resource fclose() function is used.

Create a File with PHP


When we use the function fopen() to open a file which doesn't exist then that file gets created.
Let's take an example,
$myfile = 'file.txt';
//opens the file.txt file or implicitly creates the file
$handle = fopen($myfile, 'w') or die('Cannot open file: '.$myfile);
fopen() function takes the filename as the first argument and the second argument represents
the mode in which the file will be opened.
But, if a file is not present, and you are using fopen() to create a file, then you should keep the
mode as w, which means write mode. We will learn about the various modes in the section below.

Open a File with PHP


To open a file, the same fopen() function is used. There can be many reasons behind opening a
file, like reading content of the file, writing new content to a file or appending additional content to
the already existing content in the file.
Let's take a simple example, and then we will talk about the different modes in which a file can be
opened.
$myfile = 'file.txt';
//opens the file.txt file
$handle = fopen($myfile, 'w') or die('Cannot open file: '.$myfile);
Again, fopen() function takes two mandatory arguments, one is the filename and the second one
represents the mode.
Following are the different modes along with the literal which should be passed as argument in
the fopen() function.
Mode String Description
Literal

Write mode w If the file exists then it is opened to allow write operation in it and if
it doesn't exist, then a new file is created. In this mode all the
existing data in file gets erased.

Read mode r File is opened in read mode with the file pointer starting from the
beginning of the file.

Append a File is opened in write mode where existing content of the file is
mode note erased. The new content in added after the existing content.

Create x A new file is created with write-only access. If the file already exists
Write-only then error is returned.
file
Apart from the mode specified above, we can add + along with the string literals to allow both
read and write(default) operation for a given mode.
For example, r+ mode opens file for read and write both. w+, a+ allow read operation on the file
along with the default write and append operations respectively.
Technically, file is not opened, fopen() binds the resource(file) to a stream, which can then be
used to read from the file or write data to the file.
Also, the filename should be fully qualified name along with relative path if the file is a local file.
The filename can also be a URL to specify a remote fiel's path. In that case, once PHP realise
that the file path is not local, it will check for the value of allow_url_fopen property in
the php.ini(PHP's configuration file). If it is false, PHP will print a warning and fopen() call will
fail.

Close a File with PHP


It is good practice to close a file resource after using it. In PHP fclose() function is used to close
a file resourcse. It takes the file name as argument or the variable holding the file resource
pointer as argument. Let's take an example:
$myfile = 'file.txt';
//opens the file.txt file or implicitly creates the file
$handle = fopen($myfile, 'w') or die('Cannot open file: '.$myfile);

// closing a file
fclose($handle);

Time for an Example


Let's take a simple example where we will create a PHP file to create a text file and then open
the same file to write content in it.
In the picture below we have described the directory structure which will help you to understand
how to provide the path of the file and use it in the PHP file.

Below is the code we will keep in the read-file.php file to open file.txt text file to write data in it.
$myfile = 'include/file.txt';
//opens the file.txt file
$handle = fopen($myfile, 'w') or die('Cannot open file: '.$myfile);
// close a file
fclose($handle);
We can either provide complete path for the file to be read or we can provide relative path like in
the example above.
In the upcoming tutorials we will learn how to read, write, append data to a file.

Read a File in PHP 5


Reading content from a file in PHP can be accomplished in two ways:
 Using readfile() function

 Using fread() to read content from an open file.

Read File using readfile()


The readfile() function reads the entire content of a file and writes it to the output buffer.
If we have a file matrusri-info.txt with the following content:
Following are some of the subjects available on Matrusri:
C Language
C++
Data Structure
Android
Python
We can read the entire content of the above file and write it to the output buffer using
the readfile()function.
<?php
echo readfile("matrusri-info.txt");
?>
Open and Read the File using fread()
We can read content from an already open file using the fread() function. The fread() function takes
two arguments:
1. first is the filename

2. and the second argument specifies the size in bytes for the content to be read.
Let's take an example, if we have a file matrusri.txt with following content:
Matrusri is for coding enthusiasts!
If we want to read entire content of the file, we will open the file in read mode and then use
the fread() function.
<?php
// Opening a file
$myfile = fopen("matrusri.txt", "r");

// reading the entire file using


// fread() function
echo fread($myfile, filesize("matrusri.txt"));

// closing the file


fclose($myfile);
?>

Matrusri is for coding enthusiasts!


As you can see in the above code snippet, we have used filesize() function to specify size in bytes
equal to the entire file size, hence the fread() function reads entire content of the file.
But if you want to print only partial content from the file, you can directly specify the size in bytes(1
byte = 1 character) in the second argument like below,
<?php
// Opening a file
$myfile = fopen("matrusri.txt", "r");

// reading only 12 bytes using


// fread() function
echo fread($myfile, 12);

// closing the file


fclose($myfile);
?>

Matrusri

Read File Line by Line using fgets()


The fgets() function reads a single line(till the new line character) from any given file.
Remember the matrusri-info.txt file, lets use that file in the example below,
<?php
// Opening a file
$myfile = fopen("matrusri-info.txt", "r");

// reading a single line using fgets()


echo fgets($myfile);
// closing the file
fclose($myfile);
?>

Following are some of the subjects available on Matrusri:


After a call to the fgets() function the file pointer moves to the next line, so if we call
the fgets()function twice, we will get two lines from the file,
<?php
// Opening a file
$myfile = fopen("matrusri-info.txt", "r");

// reading the first line using fgets()


echo fgets($myfile) . "<br>";
// reading the second line
echo fgets($myfile);

// closing the file


fclose($myfile);
?>

Following are some of the subjects available on Matrusri:


C Language

Get End of File using feof()


The function feof() returns true if the file pointer is at the end of file, else it returns false.
This function can be used to loop through file of unknown size because feof() function can be used to
check if the end-of-file is reached.
Let's use the feof() and fgets() function to read and echo/print the content of the file matrusri-
info.txt line by line.
<?php
// Opening a file
$myfile = fopen("matrusri-info.txt", "r");

// loop around the file to output the content


// line by line
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}

// closing the file


fclose($myfile);
?>

Read File Character by Character - fgetc()


We can use the function fgetc() to read single character from any file resource starting from the
beginning.
We can use the fgetc() function along with feof() function to print the entire content of a file,
character by character.
This function comes in handy if you have to replace any character or look for any particular character
in file content.
Let's take an example,
<?php
// Opening a file
$myfile = fopen("matrusri-info.txt", "r");

// loop around the file to output the content


// character by character
while(!feof($myfile)) {
echo fgetc($myfile);
}

// closing the file


fclose($myfile);
?>

Following are some of the subjects available on Matrusri:C LanguageC++Data StructureAndroidPython

Write or Append data to File in PHP 5


To write content to a file we can use fwrite() function in PHP. To use fwrite() function to write
content to a file, we first need to open the file resource in write or append mode.

Write to a File with PHP


fwrite() function is used to write content to a file when a file is already open in write mode.
Let's take an example, where we will write a couple of movie names to our file movies.txt
$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'w') or die('Cannot open file: '.$file_name);
$movie_name = "The Man from Earth \n";
// write name to the file
fwrite($myfile, $movie_name);

// lets write another movie name to our file


$movie_name = "SouthPaw \n";
fwrite($myfile, $movie_name);
// close the file
fclose($myfile);
In the code above we wrote two movie names in the file movies.txt. f we open the file, it will look
like following:
The Man from Earth
SouthPaw
NOTE: When a file is opened in write mode, all the existing data in the file is erased and new
data can be written to the file using the fwrite() function.
If we again open the above file to write more content to it, and we open the file in write
mode then all the existing content will be erased.

Append data to a File with PHP


If we wish to add more movie names to the file movies.txt then we need to open the file
in append mode. Let's take an example and see.
$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'a') or die('Cannot open file: '.$file_name);
$movie_name = "Avengers \n";
// write name to the file
fwrite($myfile, $movie_name);

// lets write another movie name to our file


$movie_name = "Real Steel \n";
fwrite($myfile, $movie_name);
// close the file
fclose($myfile);

The Man from Earth


SouthPaw
Avengers
Real Steel

Regular Expressions
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 a 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.
Lets 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

1 [0-9]
It matches any decimal digit from 0 through 9.
2 [a-z]
It matches any character from lower-case a through lowercase z.

3 [A-Z]
It matches any character from uppercase A through uppercase Z.

4 [a-Z]
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

1 p+
It matches any string containing at least one p.

2 p*
It matches any string containing zero or more p's.

3 p?
It matches any string containing zero or one p's.

4 p{N}
It matches any string containing a sequence of N p's

5 p{2,3}
It matches any string containing a sequence of two or three p's.

6 p{2, }
It matches any string containing a sequence of at least two p's.

7 p$
It matches any string with p at the end of it.

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

Examples
Following examples will clear your concepts about matching characters.
Sr.No Expression & Description

1 [^a-zA-Z]
It matches any string not containing any of the characters ranging from a
through z and A through Z.

2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.

3 ^.{2}$
It matches any string containing exactly two characters.

4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.

5 p(hp)*
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

1 [[:alpha:]]
It matches any string containing alphabetic characters aA through zZ.

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

4 [[:space:]]
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

1 ereg()
The ereg() function searches a string specified by string for a string
specified by pattern, returning true if the pattern is found, and false
otherwise.

2 ereg_replace()
The ereg_replace() function searches for string specified by pattern and
replaces pattern with replacement if found.

3 eregi()
The eregi() function searches throughout a string specified by pattern for
a string specified by string. The search is not case sensitive.

4 eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except
that the search for pattern in string is not case sensitive.

5 split()
The split() function will divide a string into various elements, the
boundaries of each element based on the occurrence of pattern in string.

6 spliti()
The spliti() function operates exactly in the same manner as its sibling
split(), except that it is not case sensitive.

7 sql_regcase()
The sql_regcase() function can be thought of as a utility function,
converting each character in the input parameter string into a bracketed
expression containing two characters.

You might also like