You are on page 1of 29

PHP

Introduction
All scripting languages are programming languages. The theoretical difference between the two is
that scripting languages do not require the compilation step and are rather interpreted
PHP was created by Rasmus Lerdorf in 1994 and was publicly released in June 1995.(Personal
Home Page)
In November 1997 the second version of PHP/FI being released
PHP 3 was released in 1998,. Two programmers, Zeev Suraski and Andi Gutmans, rewrote the base
of the original version and launched PHP 3. ( Hypertext Preprocessor.)
PHP 4 was released in 2000
PHP 5 was released in 2004
PHP 5 is the version currently in use on most websites and included several new features such as
support for object-oriented programming, a consistent interface for database access
PHP is the Web development language. PHP stands for PHP: Hypertext Pre-processor. The product
was originally named Personal Home Page Tools. PHP is a server-side scripting language, which
can be embedded in HTML or used as a standalone. 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:
● PHP is an Interpreted language; hence it doesn't need a compiler.
● To run and execute PHP code, we need a Web server on which PHP must be installed.
● 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.
● PHP is open source and free.

PHP source code is embedded in an HTML-based document, and is identified by special delimiting
tags,
<?php content ?>

PHP – Variable
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.
All variables in PHP are denoted with a leading dollar sign ($). Variables need not be declared
before assignment.
Syntax:
<?php
$variableName = value;
?>
Rules for naming a variable is
A variable name can consist of numbers, letters, underscores. Variable names must begin with a
letter or underscore character.

PHP Data types

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
Integers − An Integer data type is used to store any non-decimal numeric value. An integer value
can be negative or positive, but it cannot have a decimal.
Float − Float data type is used to store any decimal numeric value.
Booleans − A boolean data type can have two possible values, either True or False.
NULL − NULL data type is a special data type which means nothing. 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.
Strings − String data type in PHP is a sequence of characters enclosed within quotes. You can use
single or double quotes.
Arrays – Arrays are named and indexed collections of other values.
Objects – Objects are instances of programmer-defined classes.
Resources – Resources are special variables that hold references to resources external to PHP.

Constants
Constants are variables whose value cannot be changed. In other words, a constant value cannot
change during the execution of the script. A constant name starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.
In PHP, there are two ways to define a constant:
1. Using the define() method.
2. Using the const keyword.
While naming a constant, we don't have to use $ symbol with the constant's name.
1. Using define()
Below is the syntax for using the define() function to create a constant.
define(name, value, case-insensitive)
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.
e.g
define(pi,3.14)
2. Using the const Keyword
We can also define constants in PHP using the const keyword.
e.g
const pi=3.14

Operator
Operators are symbols that tell the PHP processor to perform certain actions.
PHP language supports following type of operators.
● Arithmetic Operators
● Comparison Operators
● Logical (or Relational) Operators
● Assignment Operators
● Conditional (or ternary) Operators
● String Operator
● Assignment Operators

Arithmetic Operators

The arithmetic operators are used to perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
Operator Type Description

+ Addition Calculates the sum of two operands

- Subtraction Calculates the difference between two operands

* Multiplication Multiplies two operands

/ Division Divides two operands

% Modulus Returns the remainder from dividing the first operand by the second

Comparison Operators
The comparison operators are used to compare two values in a Boolean fashion.

Operator Type Description

== Equal to Returns true if first operand equals second

!= Not equal to Returns true if first operand is not equal to second

<> Not equal to Returns true if first operand is not equal to second

=== Identical to Returns true if first operand equals second in both value and
type

!== Not identical to Returns true if first operand is not identical to second in both
value and type

< Less than Returns true if the value of the first operand is less than the
second.

> Greater than Returns true if the value of the first operand is greater than the
second

<= Less than or Returns true if the value of the first operand is less than, or equal
equal to to, the second

>= Greater than or Returns true if the value of the first operand is greater than, or
equal to equal to, the second

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

Operator Type Description


&& AND Performs a logical "AND" operation.
|| OR Performs a logical "OR" operation.
Xor XOR Performs a logical "XOR" (exclusive OR) operation.

Increment and Decrement Operators


The increment/decrement operators are used to increment/decrement a variable's value.
++$a Pre Increment, Increments $a by one, then returns $a
$a++ Post Increment Returns $a, then increments $a by one
--$b Pre Decrement Decrements $a by one, then returns $a
$b-- Post Decrement Returns $a, then decrements $a by one

Conditional operator(
The ternary operator is a conditional operator that decreases the length of code while performing
comparisons . This method is an alternative for using if-else and nested if-else statements.

Syntax:
e.g (Condition) ? (Statement1) : (Statement2);

Condition: It is the expression to be evaluated which returns a boolean value.


Statement 1: it is the statement to be executed if the condition results in a true state.
Statement 2: It is the statement to be executed if the condition results in a false state.
e.g
<?php
$marks=40;
print ($marks>=40) ? "pass" : "Fail";
?>

String Operator

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


strings.

Concatenation .= (dot equal to) It is used to append one string to another.


Assignment

1. Assignment operators
The assignment operators are used to assign values to variables.

Operator Description

= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign quotient
%= Divide and assign modulus

Difference between identical operator and equality operator


2. Equal Operator ==
The double equal sign == is a comparison operator called Equal Operator, it accepts two inputs to
compare and return true if the values are same and return false if values are not same.

1. Example
<?php
$a = 123;
$b = '123';
if ($a == $b) {
echo 'Values are same';
}
else {
echo 'Values are not same';
}
?>
The above example prints Values are same.
3. Identical Operator ===
Identical operator = = = allows for stricter comparison between variables. It only returns true if the
two variables or values being compared hold the same information and are of the same data type.

Example = = =
<?php
$a = 123;
$b = '123';
if ($a === $b) {
echo 'Values and types are same';
}
else {
echo 'Values and types are not same';
}
?>
The above example prints Values and types are not same because $a data type is an integer
and $b data type is string, and these data types are not same. Identical matches both a variable's
value and data type, whereas equal matches only value

4. Conditional Statements
A conditional statement is also known as a decision statement. A decision statement is used for
executing commands based on some situation or conditions. There are four types of conditional
statements in PHP, which are as follows.
● The if statement
● The if...else statement
● The if...elseif....else statement
● Switch …. Case Statement
The if Statement
The if statement is used to execute a block of code only if the specified condition
evaluates to true. This is the simplest PHP's conditional statements and can be
written like:
Syntax
if (condition) {
code to be executed if condition is true;
}
Flow chart
e.g
<?php
$a=10
if ($a%2==0)
{
echo “Even Number”;
}
?>
The if...else Statement
The if...else statement allows you to execute one block of code if the specified condition is
evaluates to true and another block of code if it is evaluates to false.
Syntax:
if (condition)
{
block_of_code_1
}
else
{
block_of_code_2
}
block_of_code_1: This would execute if the given condition is true
block_of_code_2: This would execute if the given condition is false
e.g
<?php
$a=5
if ($a%2==0)
{
echo “Even Number”;
}
else
{
echo “Odd Number”;
?>
The if...elseif....else Statement

We can check multiple conditions using this statement.

Syntax:
if (condition)
{
code to be executed if this condition is true;
}
elseif (condition)
{
code to be executed if this condition is true;
}
else
{
code to be executed if all conditions are false;
}

Example
<?php
$x = 20;
if($x > 0)
{
echo "$x is Positive Number";
}
elseif($x == 0)
{
echo "$x is zero";
}
else
{
echo "$x is Negative Number";
}
Flow Chart

Switch Statement
The switch statement has multiple choices. In the switch statement we use the case, default and
break keywords. The case keyword is used to specify each choice. The default keyword is used to
execute a statement when no case matches any switch expression. The break keyword is used to
terminate the switch case.

Syntax
switch(variable){
case value1:
// code block 1
break;
case value2:
// code block 2
break;
default:
// default code block
break;
}
Let’s examine the switch statement syntax in more detail:
⮚ First, you put a variable or expression that you want to test within parentheses after
the switch keyword.
⮚ Second, inside the curly braces are multiple case constructs where you put the values you
want to compare with the variable or expression. In case the value of the variable or
expression matches the value in a case construct, the code block in the
corresponding case construct will execute. If the value of the variable or expression does not
match any value, the code block in the default construct will execute.
⮚ Third, the break statement is used in each case or default construct to exit the entire switch
statement.

Flow chart

Example
PHP program to find even or odd using Switch statement
<?php
$n=5;
switch ($n%2)
{
case 0:
echo “Even Number “;
break;
case 1:
echo “Odd Number “;
}
?>
Looping Statement
A Loop is an Iterative Control Structure that involves executing the same number of code a number
of times until a certain condition is met.

The While Loop


The While statement executes a block of code if and as long as a specified condition evaluates to
true. If the condition becomes false, the statements within the loop stop executing and control
passes to the statement following the loop. The While loop syntax is as follows:

while (condition)
{
code to be executed;
}

Example
<?php
$i = 1;
while($i <= 10)
{
$i++;
echo "The number is " . $i . "<br>";
}
?>
Do...While Loop
The Do...While statements are similar to While statements, except that the condition is tested at the
end of each iteration, rather than at the beginning. This means that the Do...While loop is
guaranteed to run at least once. The Do...While loop syntax is as follows:
do
{
code to be exected;
}
while (condition);
<?php
$i = 1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 10);
?>
Difference Between while and do…while Loop
The while loop differs from the do-while loop in one important way — with a while loop, the
condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional
expression evaluates to false, the loop will never be executed.

With a do-while loop, on the other hand, the loop will always be executed once, even if the
conditional expression is false, because the condition is evaluated at the end of the loop iteration
rather than the beginning.

for Loop
The for loop repeats a block of code as long as a certain condition is met. It is typically used to
execute a block of code for certain number of times. For this reason, the For loop is known as a
definite loop. The for loop syntax is as follows:
for (initialization; condition; increment)
{
code to be executed;
}
The for statement takes three expressions inside its parentheses, separated by semi-colons. When
the for loop executes, the following occurs:
1. The initializing expression is executed. This expression usually initializes one or more loop
counters.
2. The condition expression is evaluated. If the value of condition is true, the loop statements
execute. If the value of condition is false, the For loop terminates.
3. The update expression increment executes.
Example
<?php
for($i=1; $i<=3; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
foreach Loop
The foreach loop is a variation of the for loop and allows you to iterate over elements in an array.
There are two different versions of the foreach loop. The foreach loop syntaxes are as follows:
foreach (array as value)
{
code to be executed;
}

foreach (array as key => value)


{
code to be executed;
}
Example
<?php
$colors = array("Red", "Green", "Blue");
foreach($colors as $value)
{
echo $value . "<br>";
}
?>

Break and Continue Statement in PHP

Break

A break statement can be used to terminate or to come out from the loop. It can be used in switch
statement to break and come out from the switch statement after each case expression. Whenever,
break statement is encounter within the program then it will break the current loop or block. A
break statement is normally used with if statement.
Example

?php

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


{
if ($i > 5)
break; // terminate loop
echo "$i"."</br>" ;
}

?>

Another Example

<?php
/* Using optional argument. */

$i = 0;
while ($i++)
{
switch ($i)
{
case 5:
echo "case 5 \n" ;
break; /* Exit only the switch. */
case 10:
echo "case 10; quitting \n" ;
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>
Continue

A continue statement can be used into the loop when we want to skip some statement to be executed
and continue the execution of above statement based on some specific condition. Continue is also
used with if statement. When compiler encounters continue, statements after continue are skipped
and control transfers to the statement above continue.
The following example uses the continue statement to print odd numbers

<?php

for ( $i = 51 ; $i <= 100 ; $i++ )


{
if($i % 2==0 )
continue ;

echo " $i "."</br>" ;


}

?>
echo and print statement
In PHP there are various methods to print data. PHP provides more functions and language
constructs for printing various data types.
print()
The print() is used to create PHP print statement to print given data to the browser. It accepts single
data and prints it on the browser. It is a PHP language construct and not a function. So, we can use
‘print’ without parenthesis for creating a print statement.
Display Strings of Text
<?php
print "Apple";
echo ("Apple");
?>
Display HTML Code
<?php
print "<h1>This is a simple heading.</h1>";
?>
Display Variables
<?php
$num=234;
Print $num;
?>

echo()
The echo statement can display anything that can be displayed to the browser, such as string,
numbers, variables values, the results of expressions etc.
Since echo is a language construct not actually a function, you can use it without
parentheses The echo() will accept multiple data separated by commas. While sending multiple
values to the echo() statement, we have to use parenthesis to enclose the values. If we use single
data in an echo() statement, we can ignore parenthesis.
e.g

Display Strings of Text


<?php
echo "Apple";
echo ("Apple","Orange","Grapes");
?>
Display HTML Code
<?php
echo "<h1>This is a simple heading.</h1>";
?>
Display Variables
<?php
$num=234;
echo $num;
?>
Difference between Echo and Print in PHP:

Echo Print

echo does not return any value. print always returns an integer value, which is 1.

We can pass multiple strings separated by Using print, we cannot pass multiple arguments.
comma (,) in echo.

echo is faster than print statement. print is slower than echo statement.

.
PHP Comments
Comments on source code will be useful for denoting the details the code logic. For an example, if
we define a function in our program, we should add comment lines to state about the parameters
passed to the function, what the function is doing and what it returns. These comment lines will be
useful to understand the code easily. Adding comments on source code is the best programming
practice.
PHP supports two types of commenting styles; those are the single-line comment and the multi-line
comment.
Single line comment
The (//) or hash(#) characters are used to add single line comments. Single line comment can also be
referred as the inline comment.
Multi-line comment style
We have to use /* and */ delimiters to add multi-line comments. By supporting multi-line statement
in a comment line, we can add descriptive comments on our source code

How to Retrieve HTML Form Data with PHP

HTML Form
An HTML form is used to collect user input. The user input can then be sent to a server for
processing. An HTML form contains form elements.
Form elements are different types of input elements, like: text fields, checkboxes, radio buttons,
submit buttons, and more.

The HTML <form> tag is used to create an HTML form and it has following syntax −
<form action = "Script URL" method = "GET | POST">
form elements like input, textarea etc.
</form>

To set up a form for server processing and data retrieval, two important form attributes that controls
how the form data is processed whenever it is submitted must be specified. These two form
attributes are:
● Method Attributes
● Action Attributes

<form action="" method=""> ... </form>

Action Attributes: specifies the PHP script file location for processing when it is submitted. If no
script file location is specified, the browser submits the form by using the current PHP script file
location.
Method Attributes: specifies what type of method the form will use to send the data. We have two
methods, the GET and POST. By default, if no method is specified, the GET method is used.
The element's name attribute value is used by PHP as key to enable access to the data value
of the specified form field element when you submit the form. Without the name attribute specified
for each element contained in the form, PHP will be unable to create an array automatically with an
access key by using the element's name attribute value.

Client browsers can send information to a web server in two different ways:
1. GET Method
2. POST Method

GET Method
This method instructs the browser to send the encoded information (the name/value pairs) through
the URL parameter by appending it to the page request. The browser implements this method by
concatenating the question mark character (?) to the end of the page request.
When you submit a form through the GET method, PHP provides a super global variable,
called $_GET. PHP uses this $_GET variable to create an associative array with keys to access all
the sent information (form data). The keys are created using the element's name attribute values.
POST Method
The form POST method sends information via HTTP header. All information sent through this
method is invisible to anyone else since all the information is embedded within the body of the
HTTP request.
When you submit a form to a server through the POST method, PHP provides a super global
variable called $_POST. The $_POST variable is used by PHP to create an associative array with an
access key. PHP uses the form field element name attribute to create the key.
Difference between GET and POST Methods
There are two ways the browser client can send information to the web server.
GET Method
● The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? Character.
● The GET method is restricted to send upto 1024 characters only.
● Never use GET method if you have password or other sensitive information to be sent to the
server.
● GET can't be used to send binary data, like images or word documents, to the server.
● The data sent by GET method can be accessed using QUERY_STRING environment
variable.
● The PHP provides $_GET associative array to access all the sent information using GET
method.
POST Method
● The POST method transfers information via HTTP headers.
● The POST method does not have any restriction on data size to be sent.
● The POST method can be used to send ASCII as well as binary data.
● The data sent by POST method goes through HTTP header so security depends on HTTP
protocol.
● The PHP provides $_POST associative array to access all the sent information using POST
method.
User defend function
A function is a block of statements that can be used repeatedly in a program. A function will not
execute automatically when a page loads. A function will be executed by a call to the function.
Syntax:
function function_name($argument1,$argument2,.....)
{
Code to be executed;
return;
}

Example
<?php
function add($a,$b)
{
$c=$a+$b;
return $c;
}
$r=add(10,30);
echo “Result is $r”;
?>
Few Rules to name Functions
A function name can only contain alphabets, numbers and underscores. No other special character
is allowed.
The name should start with either an alphabet or an underscore. It should not start with a number.
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.

When creating functions in PHP it is possible to provide default parameters so that when a
parameter is not passed to the function it is still available within the function with a pre-defined
value. These default values can also be called optional parameters because they don't need to be
passed to the function.

Example
<?php
$c=1;
function power($a,$b=2)
{
for($i=1;$i<=$b;$i++)
{
$c=$c*$a;
}
return $c;
}
echo power(3,3);
echo power (3);
?>
Output
27
9
String Functions
PHP has a vast selection of built-in string handling functions that allow you to easily manipulate
strings in almost any possible way. String functions are built-in language constructs and functions
that are designed to manipulate and display strings.
1. explode()
The explode function splits a string by a given delimiter and returns an array with all the substrings
between the delimiters
Syntax:
explode(delimiter, string)
delimiter - What character you want to split the string by
string - The original string
Example
<?php
$str="Toyota,BMW,Honda,Mercedes”;
$a=explode(“,”,$str);
pint_r($a);
?>
Output
Array
(
[0] => Toyota
[1] => BMW
[2] => Honda
[3] => Mercedes
)
2. strlen() function returns the length of a string.
<?php
echo strlen("Hello world!");
?>
output
12
3. str_word_count() function is used to count numbers of words in given string.
<?php
echo str_word_count("Hello world!");
?>
Output
2
4. strrev() function is used to revers any string.
Example
<?php
echo strrev("Hello world!");
?>
output
!dlrow olleH
5. strpos() function is used to search specific position of any words in given string.
Example
<?php
echo strpos("Hello world!", "world");
?>
Output
6
6. str_replace() function is used to replaces some characters with some other characters in a
string.
Example
<?php
echo str_replace("world", "Glob", "Hello world!");
?>
Output
Hello Glob
7. ucwords() function is used to convert first latter of every word into upper case.
<?php
$str="hellow world”;
$str=ucwords($str);
echo $str;
?>
Output
Hello World
8. strtolower() function is used to convert uppercase latter into lowercase letter.
9. strtoupper() function is used to convert lowercase latter into uppercase latter
10. substr() function Returns a Part of a String
Syntax:
substr(string, start,length)
The first argument is the string itself, second argument is the starting index of the substring
to be extracted and the third argument is the length of the substring to be extracted.
Example
<?php
echo substr(“computer”,3,3);
?>
output
mpu
11. str_repeat()
Syntax:
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.
Example
<?php
echo str_repeat(“Web”,5)
?>
Output
WebWebWebWebWeb
12. strcmp()
Syntax
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
Example
<?php
$s1=”PIN”;
$s2=”PEN”;
echo strcmp($s1,$s2);
echo strcmp($s2,$s1);
echo strcmp($s1,$s1);
?>
Output
4
-4
0
The ASCII value of “I” is 73 and ASCII value of “E” is 69 so the difference is 4 ie 73-69=4

Cookies and Sessions

Session
PHP session is used to store and pass information from one page to another temporarily A session
is a global variable stored on the server. Each session is assigned a unique id which is used to
retrieve stored values. Whenever a session is created, a cookie containing the unique session id is
stored on the user’s computer and returned with every request to the server. Session variables are
stored in the $_SESSION array variable. Sessions have the capacity to store relatively large data
compared to cookies. In PHP a session must takes care of following two things:
● Session tracking information
● Storing information associated with a session.
HTTP (hypertext transfer protocol) is a stateless protocol. It means that this protocol does not
maintain state between two transactions. HTTP does not provide a way for identification that two
requests came from one user.
Creating a Session
If we want to use a session in a page we call session_start() method at the beginning of our script.
This method should be called before any output is sent.

Example
Let’s suppose we want to know the number of times that a page has been loaded, we can use a
session to do that.
The code below shows how to create and retrieve values from sessions.
<?php

session_start(); //start the PHP_session function

if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];

?>

Output:
You are visitor number 1
Destroying a Session

A PHP session can be destroyed by session_destroy() function. This function does not need
any argument and a single call can destroy all the session variables. If you want to
destroy a single session variable then you can use unset() function to unset a session
variable.
Here is the example to unset a single variable –
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables
<?php
session_destroy();
?>

Cookie
Cookie is a small piece of information that can be stored on a client side machine by PHP script. A
cookie can be set using PHP's setcookie() function.
Syntax of setcookie() function:
setcookie ( name, value, expire, path, domain,secure);
name - Specifies the name of the cookie.
value - Specifies the value of the cookie.
Expire - Specifies when the cookie expires.
Path - Specifies the server path of the cookie. If set to "/", the cookie will be available within the
entire domain.
Domain - Specifies the domain name of the cookie.
Secure - Specifies whether or not the cookie should only be transmitted over a secure
HTTPSconnection.
To access a cookie received from a client, use the PHP $_COOKIE super global array

Difference Between Session and Cookie in PHP

Cookies Sessions
Cookies are stored in browser as text file
Sessions are stored in server side.
format.
It is stored limit amount of data allowing
It is stored unlimited amount of data
4kb
It is not holding the multiple variable in
It is holding the multiple variables in sessions.
cookies.
We can access the cookies values in easily. We cannot access the session values in easily.
So it is less secure. So it is more secure.

PHP Arrays
An array in PHP is a type of data structure that allows us to store multiple elements of similar data
type under a single variable. An array can hold any number of values. Each value in an array is
called an element. You access each element via its index.
An element can store any type of value, such as an integer, a string, or a Boolean. You can mix
types within an array — for example, the first element can contain an integer, the second can
contain a string, and so on.
There are basically three types of arrays in PHP:
1. Indexed or Numeric Arrays
2. Associative Arrays
3. Multidimensional Arrays
Indexed or Numeric Arrays
These types of arrays can be used to store any type of elements, but an index is always a number.
By default, the index starts at zero, so the first element has an index of 0; the second has an index of
1, and so on. These arrays can be created in two different ways.
First Method
Example
<?php
$fruits=array("Mango", "Orange", "Apple", "Banana");
?>
Second Method
<?php
$fruits[0]=”Mango”
$fruits[1]=”Orange”
$fruits[2]=”Apple”
$fruits[3]=”Banana”
?>
Looping over elements of an indexed array

PHP provides the foreach loop statement that allows you to iterate over elements of an array. To
loop over elements of an indexed array, you use the following syntax:

foreach ($array as $element) {


// process element here;
}

Example
<?php
$fruits=array(“Mango”,”Orange”,”Apple”,”Banana”);
foreach($fruits as $v)
{
echo “$v <br>”;
}
?>
Loop over an array using a for loop

<?php
$fruits=array(“Mango”,”Orange”,”Apple”,”Banana”);
for($i=0;$i<count($fruits); $i++)
{
echo $fruits[$i],”<br>”;
}
?>
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every value can
be assigned with a user-defined key of string type.
An associative array is in the form of key-value pair, where the key is the index of the array and
value is the element of the array. Here the key can be user-defined. It is similar to the numeric array,
but the keys and values which are stored in the form of a key-value pair.
First Method
$fruits=array(“M”=>”Mango”,”O”=>”Orange”,”A”=>”Apple”);
Second Method
$fruits[“M”]=”Mango”;
$fruits[“O”]=”Orange”
$fruits[“A”]=”Apple”

Loop Through an Associative Array


● Using foreach loop
<?php
$fruits=array(“M”=>”Mango”,”O”=>”Orange”,”A”=>”Apple”);
foreach($fruits as $k => $v)
{
echo $v “<br>”;
}
?>
● Using for loop
<?php
$fruits=array(“M”=>”Mango”,”O”=>”Orange”,”A”=>”Apple”);
$length = count($family);
$keys = array_keys($family);
for($i=0;$i<$length;$i++)
{
echo $fruits[$keys[$i]],”<br>”;
}
<?

Multidimensional Arrays in PHP

A multidimensional array is an array with elements that are arrays themselves. The
multidimensional array is an array in which each element can also be an array and each element in
the sub-array can be an array or further contain array within itself and so on.
Syntax

$myArray = array(
array( value1, value2, value3 ),
array( value4, value5, value6 ),
array( value7, value8, value9 )
);

e.g
<?php
$food= array('fruits'=>array('Apple', 'Orange', 'Mango', 'Banana'),
'vegitable'=>array('Tomato','Carrot','Cabbage'));
foreach($food as $k =>$f)
{
echo "<b>$k </b><br>";
foreach($f as $v)
echo "$v <br>";
}
?>
Output

fruits
Apple
Orange
Mango
Banana
vegitable
Tomato
Carrot
Cabbage
Array Function
print_r()

It is an inbuilt function that is used in PHP to print or display the information stored in a
variable. If an array is given, values will be presented in a format that shows keys and
elements.
Syntax:
print_r($variable)
variable: It is a mandatory parameter that specifies the variable to be printed.

<?php
$a=array(“Orange”,”Apple”,”Mango”);
Print_r($a);
?>
Output
Array
(
[0]=>Orange
[1]=>Apple
[2]=>Mango
)

Count ()

You can use count function to find the size of an array. If the value of array is not set or having an
empty array, then count will return 0. And, if it is not an array, then count will return 1.
Syntax:
Count(arr, mode)
arr- Array name
mode- If the optional mode parameter is set to 1, count() will recursively count the array. This is
particularly useful for counting all the elements of a multidimensional array.
Example
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'cabbage', 'onion'));

echo count($food,1);
echo count($food);
?>
Output
8
2

Sizeof ()

This function returns the size of the array or the number of data elements stored in the array. The sizeof()
function is an alias of the count() function.
Syntax
sizeof(arr, mode)
arr – array name
mode. Possible values:
● 0 - Default. Does not count all elements of multidimensional arrays
● 1 - Counts the array recursively (counts all the elements of multidimensional arrays)
Example
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'cabbage', 'onion'));
echo sizeof($food,1);
echo sizeof($food);
?>
Output
8
2

array_combine() - which creates an array using one array for keys and another for its values:
e.g
<?php
$k = array('sky', 'grass', 'orange');
$v = array('blue', 'green', 'orange');
$a = array_combine($k, $v);
print_r($a);
?>
Output
Array
(
[sky] => blue
[grass] => green
[orange] => orange
)

in_array()

The in_array() function is an inbuilt function in PHP. The in_array() function is used to check
whether a given value exists in an array or not. It returns TRUE if the given value is found in the
given array, and FALSE otherwise.
syntax:
in_array ( $val, $array_name ,$mode )
All three parameters are described below:
● $val: This specifies the element or value to be searched in the given array. It can be of
string type or integer type or any other type. If this parameter is of string type then the
search will be performed in case-sensitive manner.
● $array_name: it specifies the array in which we want to search.
● $mode: This is an optional parameter and is of boolean type. This parameter specifies the
mode in which we want to perform the search. If it is set to TRUE, then the in_array()
function searches for the value with the same type of value as specified by $val parameter.
The default value of this parameter is FALSE.
Example
<?php
$a=(20,30,40,50)
if(in_array(30,$a))
{
echo “Found”;
}
else
{
echo “Not Found “;
}
if(in_array(“30”,$a))
{
echo “Found”;
}
else
{
echo “Not Found “;
}
if(in_array(“30”,$a,TRUE))
{
echo “Found”;
}
else
{
echo “Not Found “;
}

Output
Found
Found
Not Found
array_search()
This inbuilt function of PHP is used to search for a particular value in an array, and if the value is
found then it returns its corresponding key. If there is more than one value then the key of first
matching value will be returned.
Syntax:
array_search($value, $array, mod)

This function takes three parameters as described below:


● $value - This specifies the element or value to be searched in the given array. It can be of
string type or integer type or any other type. If this parameter is of string type then the
search will be performed in case-sensitive manner.
● $array - it specifies the array in which we want to search.
● $mode: This is an optional parameter and is of boolean type. This parameter specifies the
mode in which we want to perform the search. If it is set to TRUE, then the array_search()
function searches for the value with the same type of value as specified by $val parameter.
The default value of this parameter is FALSE
Example 1
<?php
$a=array(23,45,67,89,20);
echo array_search(89,$a);
?>
Output
3

Example 2
<?php
$a= array(23,45,67,89,20,67);
echo array_search(67,$a);
?>
Output
2
Example 3
<?php
$a= array(23,45,67,89,20,67);
echo array_search(“20”,$a);
?>
Output
4

array_count_values()
The array_count_values() This function returns an associative array with key-value pairs in which
keys are the elements of the array passed as parameter and values are the frequency of these
elements in an array.
Syntax
array_count_values ($array_name);
Example
<?php
$a = array("orange", "mango", "banana", "orange", "banana" );
$b = array_count_values($a)
print_r($b);
?>
Output
Array
(
[orange] => 2
[mango] => 1
[banana] => 2
)
array_diff()
This function is used to compares an array against one or more other arrays and returns the values in
the first array that are not present in any of the other arrays.
Syntax
array_diff($array1,$array2,…..)
Example
<?php
$a = array("orange", "banana", "apple");
$b = array("orange", "mango", "apple");
$c = array_diff($a,$b);
print_r($c);
?>

Output
Array
(
[1] => banana
)

array_fill() – This function is used to fill an array with values.


Syntax
array_fill($start_index, $number_elements, $values)
$start_index: This parameter specifies the starting position of filling up the values into the
array
$number_elements: This parameter refers to the number of elements; the user wants to
enter into the array.
$values : This parameter refers to the values we want to insert into the array.
Example
<?php
$a=array(10,20,30);
$b=array_fill(3,4,"blue");
print_r($b);
?>
output
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => blue
[4] => blue
[5] => blue
[6] => blue
)
array_replace()

This function takes a list of arrays separated by commas (,) as parameters and replaces all those
values of the first array that have same keys in the other arrays.
Syntax:
array_replace ( $array1, $array2, ...., $arrayn )
Example
<?php
$a = array("Orange", "Banana", "Apple", ”Mango”)
$b = array(“Grapes” , ”Pineapple”);
$c = array_replace($a,$b);
print_r($c)
?>

Output
Array
(
[0] => Grapes
[1] => Pineapple
[3] => apple
[4] => Mango
)
array_unique()
This function removes duplicate values from an array. If there are multiple elements in the array
with same values then the first appearing element will be kept and all other occurrences of this
element will be removed from the array.
Syntax:
array_unique($array)
Example
<?php

$a=array("red", "green", "red", "blue", ”green”, ”red” );


$b= array_unique($a);
print_r($b);

?>
OUTPUT
Array
(
[0] => red
[1] => green
[3] => blue
)
array_sum()
This function returns the sum of all the values in an array. It takes an array parameter and returns
the sum of all the values in it.
Syntax
array_sum ( $array )
Example 1

<?php
$a = array(12, 24, 36, 48);
print_r(array_sum($a));
?>
OUTPUT
120
Example 2
<?php
$m=array (‘physics’=>30, ‘maths’=>25, ‘chemistry’=>40);
print_r(array_sum($m));
?>
OUPUT
95
array_reverse()
This function is used to reverse the order of the elements in an array.
Syntax
array_reverse ( $array)
Example 1
<?php
$num= array(100,200,300,400,500);
$y = array_reverse($num);
print_r($y);
?>
OUTPUT
Array
(
[0] => 500
[1] => 400
[2] => 300
[3] => 200
[4] => 100
)
Example 2
<?php
$lang = array("a"=>"PHP","b"=>"JAVA","c"=>"PYTHON");
print_r(array_reverse($lang));
?>
OUTPUT
Array
( [c] => PYTHON
[b] => JAVA
[a] => PHP
)
Sorting an array
sort() – sorts arrays in ascending order
rsort() – sorts arrays in descending order
Example for sorts arrays in ascending order
<?php
$num = array(40, 61, 2, 22, 13);
sort($num);
foreach($num as $)
echo “$x <br>”;

}
?>

OUTPUT
2
13
22
40
61
Example for sorts arrays in descending order
<?php
$num = array(40, 61, 2, 22, 13);
rsort($num);
foreach($num as $)
echo “$x <br>”;
?>

OUTPUT
61
40
22
13
2

list()
list() is used to assign the array values to multiple variables at a time. It works only on the numeric
or indexed arrays. The first element in the given array is assigned to the first variable passed and the
second element to the second variable and so on, till the number of variables passed in parameter. It
accepts a list of variables as parameter separated by comma.
Syntax
list($variable1,$variable2,…..)=$arraname
<?php
$f=array(“Mango”,”Apple”,”Grapes”);
list($a,$b,$c)=$f;
echo “$a <br>”;
echo “$b <br>”;
echo “$c <br>”;
?>
Output
Mango
Apple
Orange

You might also like