PHP Notes
PHP Notes
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code is executed on the server, and the result is returned to the browser as
plain HTML
PHP files have extension ".php"
PHP Structure
<?php echo "Hello Everyone"; ?>
with HTML
<html>
<head>
<title>PHP</title>
</head>
<body>
</body>
</html>
PHP Echo/Print
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the
screen.
The differences are small: echo has no return value while print has a return value of 1 so it
can be used in expressions. echo can take multiple parameters (although such usage is
rare) while print can take one argument. echo is marginally faster than print.
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command (notice that the
text can contain HTML markup):
echo "This ", "string ", "was ", "made ", "with multiple
parameters.";
Display Variables
The following example shows how to output text and variables with the echo statement:
Example
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo $x + $y;
Display Text
The following example shows how to output text with the print command (notice that the
text can contain HTML markup):
Example
Display Variables
The following example shows how to output text and variables with the print statement:
Example
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print $x + $y;
<?php
echo "LBSTI";
echo 'LBSTI';
echo ('LBSTI');
echo "Yahoo","Baba";
echo "Yahoo"."Baba";
echo "<h1><i>Yahoo"."Baba</i></h1>";
echo 23.58;
print "<h1><i>Yahoo"."Baba</i></h1>";
print 23.58;
?>
PHP Variables
Variables are "containers" for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
$x = 5;
$y = "John"
In the example above, the variable $x will hold the value 5, and the variable $y will hold the
value "John".
PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
$txt = "W3Schools.com";
Example
$x = 5;
$y = 4;
echo $x + $y;
Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
Example
$x = "John";
echo $x;
You can assign the same value to multiple variables in one line:
Example
$x = $y = $z = "Fruit";
<?php
$name = "LBSTI<br>";
$num = 2358;
echo $name;
echo $num;
?>
PHP Data Types
Variables can store data of different types, and different data types can do different things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
You can get the data type of any object by using the var_dump() function.
Example
The var_dump() function returns the data type and the value:
$x = 5;
var_dump($x);
PHP String
A string can be any text inside quotes. You can use single or double quotes:
Example
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
PHP Integer
In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:
Example
$x = 5985;
var_dump($x);
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
Example
$x = 10.365;
var_dump($x);
PHP Boolean
Example
$x = true;
var_dump($x);
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
Example
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Example
$x = "Hello world!";
$x = null;
var_dump($x);
<?php
$x = "LBSTI";
$x = 2500;
$x = 2500.50;
$x = true;
$x = array("html","css","js");
$x = null;
echo $x . "<br>";
?>
PHP Comment
A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.
Example
/* This is a
multi-line comment */
Any text between // and the end of the line will be ignored (will not be executed).
You can also use # for single line comments, but in this tutorial we will use //.
Example
A comment before the code:
Multi-line Comments
Example
/*
*/
The multi-line comment syntax can also be used to prevent execution of parts inside a
code-line:
Example
$x = 5 /* + 15 */ + 5;
echo $x;
<?php
echo $x;
/* Multiple Line Comment */
/* $x = "LBSTI";
echo $x; */
?>
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changed during
the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant
name).
Note: Unlike variables, constants are automatically global across the entire script.
Syntax
Example
echo GREETING;
Example
Create a constant with a case-insensitive name:
echo greeting;
<?php
define("test",50);
echo test;
define("test1",50,true);
echo TEST1;
echo $sum;
?>
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
<?php
$a = 10;
$b = 3;
$c = $a + $b;
$c = $a - $b;
$c = $a * $b;
$c = $a / $b;
$c = $a % $b;
$c = $a ** $b;
$c = $a % $b;
$a++;
++$a;
$a--;
$a;
$c = ($a + $b) * 2;
echo $c;
?>
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
x=y x=y The left operand gets set to the value of the expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
<?php
$a = 10;
$b = 3;
$a = $a + $b;
$a += $b;
$a -= $b;
$a *= $b;
$a /= $b;
$a %= $b;
$a **= $b;
echo $a;
?>
The PHP comparison operators are used to compare two values (number or string):
=== Identical $x === Returns true if $x is equal to $y, and they are of the same type
$y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same
type
<=> Spaceship $x <=> Returns an integer less than, equal to, or greater than zero,
$y depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.
<?php
$a = 10;
$b = 10;
echo $a == $b;
echo $a != $b;
?>
PHP If
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.
Syntax
if (condition) {
Example
if (5 > 3) {
<?php
$a = 3;
$b = 10;
if($a == $b):
endif;
?>
<?php
$age = 20;
/* Logical Or Operator*/
?>
The if...else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition) {
} else {
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!"
otherwise:
$t = date("H");
} else {
}
<?php
$x = 15;
}else{
$x = 100;
if($x == 100){
}else{
$name = "LBSTI";
$gender = "male";
if($gender == "male"){
}else{
echo "Hello Miss.". $name;
?>
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
} elseif (condition) {
} else {
<?php
$per = 47;
} else{
else:
endif;
?>
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
<?php
$weekday = 7;
switch($weekday){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
default:
$weekday = 3;
switch($weekday){
break;
case 4 :
echo "Today is Thursday";
break;
case 5 :
break;
case 6 :
break;
case 7 :
break;
default :
$age = 18;
switch($age){
break;
break;
default :
}
?>
There is also a short-hand if else, which is known as the ternary operator because it
consists of three operands. It can be used to replace multiple lines of code with a single
line. It is often used to replace simple if else statements:
Syntax
<?php
$x = 10;
echo $z;
?>
Strings
echo "Hello";
echo 'Hello';
You can use double or single quotes, but you should be aware of the differences between
the two.
Example
$x = "John";
<?php
$a = "Hello" ;
$a = 200;
$s = "Hello ";
$s .= 555;
echo $s;
?>
The while loop executes a block of code as long as the specified condition is true.
Example
$i = 1;
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if
the condition is still true.
The condition does not have to be a counter, it could be the status of an operation or any
condition that evaluates to either true or false.
<?php
$a = 1;
$a = $a + 1; //Increment Loop
$a = $a++; //counting
$a = 10;
echo "<ul>";
while($a >= 1){
$a = $a - 1;
echo "</ul>";
$a = $a + 2; //increament of 2 or 3
?>
The do...while loop will always execute the block of code at least once, it will then check
the condition, and repeat the loop while the specified condition is true.
Example
$i = 1;
do {
echo $i;
$i++;
<?php
$a = 1;
do{
$a = 10;
do{
}while($a <= 1)
?>
The for loop is used when you know how many times the script should run.
Syntax
// code block
<?php
//Increment
for($a = 1; $a <= 10; $a= $a++ ){
//Decrement
?>
The nested loop is the method of using the for loop inside the another for loop. It first
performs a single iteration for the parent for loop and executes all the iterations of the inner
loop. After that, it again checks the parent iteration and again performs all the iteration of
the inner loop. The same process continuously executed until the parent test condition is
TRUE.
<?php
echo "<br>";
?>
The continue statement stops the current iteration in the for loop and continue with the
next.
Example
Move to next iteration if $x = 4:
if ($x == 4) {
continue;
The continue statement stops the current iteration in the while loop and continue with the
next.
Example
$x = 0;
if ($x == 4) {
continue;
$x++;
Example
if ($x == 4) {
break;
Example
$x = 0;
if ($x == 4) {
break;
$x++;
<?php
if ($a == 3){
continue;
}
echo "Number : " . $a . "<br>";
if ($a == 3){
break;
?>
The goto statement is used to jump to another section of a program. It is sometimes referred to as an
unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere
within a function.
Syntax:
statement_1;
if (expr)
goto label;
statement_2;
statement_3;
label: statement_4;
<?php
for($a = 1; $a <= 10; $a++){
if($a == 3){
goto a;
echo "Hello";
a:
?>
PHP Functions
PHP has more than 1000 built-in functions, and in addition you can create your own custom
functions.
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform a specific task.
Besides the built-in PHP functions, it is possible to create your own functions.
A user-defined function declaration starts with the keyword function, followed by the name
of the function:
Example
function myMessage() {
Call a Function
To call the function, just write its name followed by parentheses ():
Example
function myMessage() {
myMessage();
<?php
function hello(){
function yahoo(){
hello();
hello();
yahoo();
hello();
?>
PreviousNext
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When
the familyName() function is called, we also pass along a name, e.g. ("Jani"), and the
name is used inside the function, which outputs several different first names, but an equal
last name:
Example
function familyName($fname) {
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
The following example has a function with two arguments ($fname, $year):
Example
}
familyName("Hege", "1975");
familyName("Stale", "1978");
<?php
function hello($name){
/* TWO Argument : */
function hello($fname,$lname){
hello("Yahoo","Baba");
hello("Bill","Gates");
/* Default Value : */
function hello($fname="First",$lname="Name"){
/* SUM function */
function sum($a,$b){
echo $a + $b;
sum(10,20.50);
$one = 10;
$two = 20.50;
sum($one,$two);
?>
Example
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
<?php
//1)
function hello($fname="First",$lname="Last"){
$v = "$fname $lname";
return $v;
echo hello("Yahoo","Baba");
//2)
$name = hello("Yahoo","Baba");
//3)
function sum($math,$eng,$sc){
return $s;
}
$total = sum(55,65,88);
echo $total;
//4)
function percentage($st){
$per = $st/3;
percentage($total);
?>
In PHP, arguments are usually passed by value, which means that a copy of the value is
used in the function and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change
the variable that was passed in. To turn a function argument into a reference, the & operator
is used:
Example
function add_five(&$value) {
$value += 5;
$num = 2;
add_five($num);
echo $num;
<?php
function testing(&$string)
testing($str);
echo $str;
function first($num) {
$num += 5;
function second(&$num) {
$num += 6;
$number = 10;
first( $number );
second( $number );
echo "Original Value is $number<br />";
?>
$func = "wow";
$func('Yahoo Baba');
$sayHello('Yahoo Baba');
?>
PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
Example
<?php
function display($number) {
if($number<=5){
display($number+1);
}
}
display(1);
?>
<?php
/*-----Recursive Function------ */
function display($number) {
if($number<=5){
display($number+1);
display(1);
/* --------Factorial Number--------- */
function factorial($n)
return -1;
if ($n == 0){
return 1;
}else{
echo factorial(5);
?>
The scope of a variable is the part of the script where the variable can be referenced/used.
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Example
$x = 5; // global scope
function myTest() {
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
Example
function myTest() {
$x = 5; // local scope
myTest();
<?php
$x = 10;
function test() {
test();
/* $x = 5;
$y = 10;
function test() {
$x = $x + $y;
test();
echo $x; */
?>
What is an Array?
An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name.
Create Array
Example
Multiple Lines
Line breaks are not important, so an array declaration can span multiple lines:
Example
$cars = [
"Volvo",
"BMW",
"Toyota"
];
To access an array item, you can refer to the index number for indexed arrays, and the key
name for associative arrays.
Example:
echo $cars[2];
<?php
/* -------Array---------- */
echo $colors[0]."<br>";
//2.)
echo "<pre>";
print_r($colors);
echo "</pre>";
//3.)
$colors[1] = "green"
$colors[2] = "yellow";
$colors[3] = "blue";
//4.)
echo "<li>$i</li>";
echo "</ul>";
?>
Associative arrays are arrays that use named keys that you assign to them.
Example
var_dump($car);
Example
Change Value
Example
$car["year"] = 2024;
var_dump($car);
<?php
$age = array(
"elon" => 22
);
echo '<pre>';
print_r($age);
echo '</pre>';
echo '<pre>';
var_dump($age);
echo '</pre>';
$age1 = [
"elon" => 22
];
echo '<pre>';
print_r($age1);
echo '</pre>';
echo '<pre>';
var_dump($age1);
echo '</pre>';
echo '<pre>';
print_r($age1);
echo '</pre>';
echo '<pre>';
var_dump($age1);
echo '</pre>';
$age2 = array(
10 => 28,
13 => 22
);
echo '<pre>';
print_r($age2);
echo '</pre>';
$age3 = array(
13 => 22
);
echo '<pre>';
var_dump($age3);
echo '</pre>';
?>
To loop through and print all the values of an associative array, you can use
a foreach loop, like this:
Example
To loop through and print all the values of an indexed array, you can use a foreach loop,
like this:
Example
<?php
$colors = [
"red",
"green",
"blue"
];
foreach($colors as $value){
$age = [
];
echo "<ul>";
echo "</ul>";
?>
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an
element.
<?php
$emp = [
[1,"Krishana","Manager",50000],
[2,"Salman","Salesman",20000],
[3,"Mohan","Computer Operator",12000],
[4,"Amir","Driver",5000]
];
echo "<pre>";
print_r($emp);
echo "</pre>";
/* TWO dimensional Array row and column */
echo "<br>";
echo "<br>";
}
/* Print with Table tag */
echo "<tr>
<th>Emp Id</th>
<th>Emp Name</th>
<th>Designation</th>
<th>Salary</th>
</tr>";
echo "<tr>";
echo "</tr>";
echo "</table>";
?>
<?php
$marks = [
"Krishna" => [
"physics" => 85,
"chemistry" => 89
],
"Salman" => [
"chemistry" => 79
],
"Mohan" => [
"chemistry" => 92
];
echo "<pre>";
print_r($marks);
echo "</pre>";
echo $key;
foreach($v1 as $v2){
echo "</br>";
<tr>
<th>Student Name</th>
<th>Physics</th>
<th>Math</th>
<th>Chemistry</th>
</tr>";
echo "<tr>
<td>$key</td>";
foreach($v1 as $v2){
echo "</tr>";
echo "</table>";
?>
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Syntax
count(array, mode)
Parameter Values
Parameter Description
array Required. Specifies the array
mode Optional. Specifies the mode. Possible values:
<?php
$cars=array("Volvo","BMW","Toyota");
echo sizeof($cars);
?>
Syntax
sizeof(array, mode)
Parameter Values
Parameter Description
array Required. Specifies the array
mode Optional. Specifies the 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)
<?php
$food1 = array(
);
echo sizeof($food1,1).'<br>';
echo sizeof($food1['fruits'],1).'<br>';
$len = count($food);
}
$food2 = array('orange', 'banana', 'orange' , 'apple');
echo "<pre>";
print_r(array_count_values($food2));
echo "</pre>";
?>
Syntax
Parameter Values
Parameter Description
search Required. Specifies the what to search for
array Required. Specifies the array to search
type Optional. If this parameter is set to TRUE, the in_array() function searches for the search-
string and specific type in the array.
Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise
array_search()
The array_search() function search an array for a value and returns the key.
Syntax
Parameter Values
Parameter Description
value Required. Specifies the value to search for
array Required. Specifies the array to search in
strict Optional. If this parameter is set to TRUE, then this function will search for identical elements
in the array. Possible values:
true
false - Default
When set to true, the number 5 is not the same as the string 5 (See example 2)
Return Returns the key of a value if it is found in the array, and FALSE otherwise. If the value is
Value: found in the array more than once, the first matching key is returned.
<?php
if (in_array("apple", $food)) {
}else{
/* -----------Associative Array-------------- */
$food = array('a' => 'orange', 'b' => 'banana', 'c' => 'apple', 'd'
=> 'grapes');
?>
The array_replace() function replaces the values of the first array with the values from
following arrays.
Syntax
Parameter Values
Parameter Description
array1 Required. Specifies an array
array2 Optional. Specifies an array which will replace the values of array1
array3,... Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from
later arrays will overwrite the previous ones.
The array_replace_recursive() function replaces the values of the first array with the values
from following arrays recursively.
Syntax
Parameter Values
Parameter Description
array2 Optional. Specifies an array which will replace the values of array1
array3,... Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from
later arrays will overwrite the previous ones.
<?php
print_r($newArray);
echo "</pre>";
/* ----------------Associative Array------------------- */
/* ---- array_replace_recursive----------- */
$array1 = array("a"=>array("red"),"b"=>array("green","pink"));
$array2 = array("a"=>array("yellow"),"b"=>array("black"));
?>
Syntax
array_pop(array)
Parameter Values
Parameter Description
Return Value: Returns the last value of array. If array is empty, or is not an array, NULL will be returned.
The array_push() function inserts one or more elements to the end of an array.
Syntax
Parameter Values
Parameter Description
value1 Optional. Specifies the value to add (Required in PHP versions before 7.3)
array_pop($fruit);
echo "<pre>";
print_r($fruit);
echo "</pre>";
array_push($fruit,"apple","guava","lemon");
echo "<pre>";
print_r($fruit);
echo "</pre>";
?>
Array_shift()
The array_shift() function removes the first element from an array, and returns the value of
the removed element.
Syntax
array_shift(array)
Parameter Values
Parameter Description
array Required. Specifies an array
Return Value: Returns the value of the removed element from an array, or NULL if the array is empty
Array_unshift()
The array_unshift() function inserts new elements to an array. The new array values will be
inserted in the beginning of the array.
Syntax
Parameter Values
Parameter Description
array Required. Specifying an array
value1 Optional. Specifies a value to insert (Required in PHP versions before 7.3)
value2 Optional. Specifies a value to insert
value3 Optional. Specifies a value to insert
Return Value: Returns the new number of elements in the array
<?php
array_shift($fruit);
echo "<pre>";
print_r($fruit);
echo "</pre>";
echo "<pre>";
print_r($fruit);
echo "</pre>";
?>
array_merge() Function
The array_merge() function merges one or more arrays into one array.
Syntax
Parameter Values
Parameter Description
array_combine()
The array_combine() function creates an array by using the elements from one "keys" array
and one "values" array.
Syntax
array_combine(keys, values)
Parameter Values
Parameter Description
Return Value: Returns the combined array. FALSE if number of elements does not match
<?php
$newArray = array_merge($fruit,$veggie);
echo "<pre>";
print_r($newArray);
echo "</pre>";
array_merge($fruit,$veggie,$color);
$fruit = ['a' => "orange", 'b' => "banana", 'c' => "grapes"];
$veggie = ['d' => 'carrot','e' => 'pea']; /* ---- Also with SAME
KEY */
/* ----------array_merge_recursive-------------- */
55,
68
];
$newArray = array_merge_recursive($fruit,$veggie);
/* --------array_combine-------- */
$name = array("Ram","Mohan","Salman");
$age = array("35","37","43");
echo "<pre>";
print_r($newArray);
echo "</pre>";
?>
PHP Array_Slice
Syntax
Parameter Values
Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start the slice. 0 = the first
element. If this value is set to a negative number, the function will start slicing that far from
the last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies the length of the returned array. If this value is set to a
negative number, the function will stop slicing that far from the last element. If this value is
not set, the function will return all elements, starting from the position set by the start-
parameter.
preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:
$color=array("red","green","blue","yellow","brown");
echo "<pre>";
print_r($newArray);
echo "</pre>";
print_r(array_slice($color,-2,1));
echo '<br>';
echo '<br>';
/* ---------Preserve Parameter----------- */
print_r(array_slice($color,1,2,true));
echo '<br>';
echo '<br>';
array_slice($color, 0, 3, true);
echo '<br>';
$a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"br
own");
print_r(array_slice($a,1,2));
?>
PHP Array_Splice()
The array_splice() function removes selected elements from an array and replaces it with
new elements. The function also returns an array with the removed elements.
Syntax
Parameter Values
Parameter Description
start Required. Numeric value. Specifies where the function will start removing elements. 0 = the
first element. If this value is set to a negative number, the function will start that far from the
last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies how many elements will be removed, and also length of
the returned array. If this value is set to a negative number, the function will stop that far from
the last element. If this value is not set, the function will remove all elements, starting from
the position set by the start-parameter.
array Optional. Specifies an array with the elements that will be inserted to the original array. If it's
only one element, it can be a string, and does not have to be an array.
Return Value: Returns the array consisting of the extracted elements
<?php
$color =["red","green","blue","yellow","brown"];
array_splice($color, -1);
array_splice($color, 0, 1);
array_splice($color, 0 , 2, $fruit);
array_splice($color, 2 , 2, $fruit);
/* -----------use count method in $color ------------- */
array_splice($color, 2, 0, $fruit);
array_splice($color, 0, 0, $fruit);
array_splice($color,count($color),0, $fruit);
echo "<pre>";
print_r($color);
echo "</pre>";
?>
Syntax
Parameter Values
Parameter Description
array Required. Specifies an array
value Optional. You can specify a value, then only the keys with this value are returned
strict Optional. Used with the value parameter. Possible values:
true - Returns the keys with the specified value, depending on type: the number 5 is
not the same as the string "5".
false - Default value. Not depending on type, the number 5 is the same as the string
"5".
<?php
/*-------- array_keys--------*/
$color =["red","green","blue","yellow"];
$newArray = array_keys($color);
echo '<pre>';
print_r($newArray);
echo '</pre>';
$color1 =[
"first" =>"red",
"second" =>"green",
"third" =>"blue",
"fourth" =>"yellow"
];
$newArray1 = array_keys($color1);
echo '<pre>';
print_r($newArray1);
echo '</pre>';
/* ---------Comes in 7.3---------- */
$newArray1 = array_key_first($color1);
echo '<pre>';
print_r($newArray1);
echo '</pre>';
/* ---------Comes in 7.3----------- */
$newArray1 = array_key_last($color1);
echo '<pre>';
print_r($newArray1);
echo '</pre>';
/* ------array_key_exists--------- */
$newArray1 = array_key_exists("third", $color1);
echo '<pre>';
print_r($newArray1);
echo '</pre>';
echo '<pre>';
print_r($newArray1);
echo '</pre>';
echo '<pre>';
print_r($newArray1);
echo '</pre>';
if ($newArray1)
else
{
?>
The array_intersect() function compares the values of two (or more) arrays, and returns the
matches.
This function compares the values of two or more arrays, and return an array that contains
the entries from array1 that are present in array2, array3, etc.
Syntax
Parameter Values
Parameter Description
Return Returns an array containing the entries from array1 that are present in all of the other
Value: arrays
<?php
/* -----------array_intersect-------------- */
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"red","f"=>"green","d"=>"purple");
$newArray = array_intersect($a1,$a2);
echo "<pre>";
print_r($newArray);
echo "</pre>";
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");
$newArray11 = array_intersect($a1,$a2,$a3);
echo "<pre>";
print_r($newArray11);
echo "</pre>";
$newArray1 = array_intersect_key($a1,$a2);
echo "<pre>";
print_r($newArray1);
echo "</pre>";
/* ---------Match Key and Value both---------- */
$newArray2 = array_intersect_assoc($a1,$a2);
echo "<pre>";
print_r($newArray2);
echo "</pre>";
function compare($a,$b){
if ($a===$b){
return 0;
function compareValue($a,$b){
if ($a===$b){
return 0;
}
$newArray3 = array_intersect_uassoc($a1,$a2, "compare");
echo "<pre>";
print_r($newArray3);
echo "</pre>";
echo "<pre>";
print_r($newArray4);
echo "</pre>";
echo "<pre>";
print_r($newArray5);
echo "</pre>";
echo "<pre>";
print_r($newArray6);
echo "</pre>";
$newArray7=array_uintersect_uassoc($a1,$a2,"compare","compareValue"
);
echo "<pre>";
print_r($newArray7);
echo "</pre>";
?>
The array_diff() function compares the values of two (or more) arrays, and returns the
differences.
This function compares the values of two (or more) arrays, and return an array that contains
the entries from array1 that are not present in array2 or array3, etc.
Syntax
Parameter Values
Parameter Description
Return Returns an array containing the entries from array1 that are not present in any of the
Value: other arrays
array_udiff()
The array_udiff() function compares the values of two or more arrays, and returns the
differences.
This function compares the values of two (or more) arrays, and return an array that contains
the entries from array1 that are not present in array2 or array3, etc.
Syntax
Parameter Values
Parameter Description
myfunctio Required. A string that define a callable comparison function. The comparison function must
n return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument
Return Returns an array containing the entries from array1 that are not present in any of the
Value: other arrays
<?php
$a1 = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2 = array("a"=>"red","f"=>"green","d"=>"purple");
$newArray = array_diff($a1,$a2);
echo "<pre>";
print_r($newArray);
echo "</pre>";
$a3 = array("a"=>"red","b"=>"black","h"=>"yellow");
$newArray1 = array_diff($a1,$a2,$a3);
echo "<pre>";
print_r($newArray1);
echo "</pre>";
$newArray2 = array_diff_key($a1,$a2);
echo "<pre>";
print_r($newArray2);
echo "</pre>";
/* -------Compare Key and Value both ---- Only compare associative
array------- */
$newArray3 = array_diff_assoc($a1,$a2);
echo "<pre>";
print_r($newArray3);
echo "</pre>";
function compare($a,$b)
if ($a===$b){
return 0;
function compareValue($a,$b)
if ($a===$b){
return 0;
echo "<pre>";
print_r($newArray4);
echo "</pre>";
echo "<pre>";
print_r($newArray5);
echo "</pre>";
echo "<pre>";
print_r($newArray6);
echo "</pre>";
$newArray7 = array_udiff_uassoc($a1,$a2,"compare","compareValue");
echo "<pre>";
print_r($newArray7);
echo "</pre>";
?>
The array_values() function returns an array containing all the values of an array.
Syntax
array_values(array)
Parameter Values
Parameter Description
array_unique()
The array_unique() function removes duplicate values from an array. If two or more array
values are the same, the first appearance will be kept and the other will be removed.
Syntax
array_unique(array, sorttype)
Parameter Values
Parameter Description
sorttype Optional. Specifies how to compare the array elements/items. Possible values:
<?php
/* ------------Array Values------------ */
$a1 = array("a"=>"red","b"=>"green","c"=>"red","d"=>"yellow");
$newArray = array_values($a1);
echo "<pre>";
print_r($newArray);
echo "</pre>";
/* ---------Array Unique---------*/
$newArray1 = array_unique($a1);
echo "<pre>";
print_r($newArray1);
echo "</pre>";
?>
array_column() Function
The array_column() function returns the values from a single column in the input array.
Syntax
Parameter Values
Parameter Description
array Required. Specifies the multi-dimensional array (record-set) to use. As of PHP 7.0, this can
also be an array of objects.
column_key Required. An integer key or a string key name of the column of values to return. This
parameter can also be NULL to return complete arrays (useful together with index_key to
re-index the array)
index_key Optional. The column to use as the index/keys for the returned array
Return Value: Returns an array of values that represents a single column from the input array
Array_Chunk()
Syntax
Parameter Values
Parameter Description
array Required. Specifies the array to use
size Required. An integer that specifies the size of each chunk
preserve_key Optional. Possible values:
Return Returns a multidimensional indexed array, starting with zero, with each dimension
Value: containing size elements
<?php
/*------------Array_Column------------ */
$array = array(
array(
),
array(
),
array(
);
$newArray = array_column($array,'first_name');
echo "<pre>";
print_r($newArray);
echo "</pre>";
$newArray1 = array_column($array,'first_name','id');
echo "<pre>";
print_r($newArray1);
echo "</pre>";
/* -------Array chunk------- */
$cars = ["Volvo","BMW","Toyota","Honda","Mercedes","Opel"];
$newArray2 = array_chunk($cars,3);
echo "<pre>";
print_r($newArray2);
echo "</pre>";
$age = array(
echo "<pre>";
print_r($newArray3);
echo "</pre>";
?>
The array_flip() function flips/exchanges all keys with their associated values in an array.
Syntax
array_flip(array)
Parameter Values
Parameter Description
array Required. Specifies an array of key/value pairs to be flipped
array_chunk() Function
Syntax
Parameter Values
Parameter Description
array Required. Specifies the array to use
size Required. An integer that specifies the size of each chunk
preserve_key Optional. Possible values:
true - Preserves the keys
false - Default. Reindexes the chunk numerically
Return Returns a multidimensional indexed array, starting with zero, with each dimension
Value: containing size elements
<?php
/*--------Array Flip---------*/
$a = array(
"Bill" =>10,
"Peter" => 30
);
$newArray = array_flip($a);
echo "<pre>";
print_r($newArray);
echo "</pre>";
/* -----array_change_key_case----- */
$newArray2 = array_change_key_case($a);
echo "<pre>";
print_r($newArray2);
echo "</pre>";
//default is lower case
/* --------CASE_UPPER or CASE_LOWER-------- */
echo "<pre>";
print_r($newArray3);
echo "</pre>";
?>
The array_sum() function returns the sum of all the values in the array.
Syntax
array_sum(array)
Parameter Values
Parameter Description
Syntax
array_product(array)
Parameter Values
Parameter Description
array Required. Specifies an array
$a2 = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
/*------------Array Sum------------ */
/*------------Array Product------------ */
?>
The array_rand() function returns a random key from an array, or it returns an array of
random keys if you specify that the function should return more than one key.
Syntax
array_rand(array, number)
Parameter Values
Parameter Description
Return Returns a random key from an array, or an array of random keys if you specify that the
Value: function should return more than one key
<?php
/*------------Array Rand------------ */
$color = array("red","green","blue","yellow","brown");
$newArray = array_rand($color);
echo "<pre>";
print_r($newArray);
echo "</pre>";
echo $color[$newArray]."<br><br>";
echo $color[$newArray1[0]]."<br>";
echo $color[$newArray1[1]]."<br>";
/*------------Use with Associative Array------------ */
$color1 = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
echo "<pre>";
print_r($newArray2);
echo "</pre>";
/*------------Shuffle Array------------ */
$color2 = array("red","green","blue","yellow","brown");
shuffle($color2);
echo "<pre>";
print_r($color2);
echo "</pre>";
shuffle($color3);
echo "<pre>";
print_r($color3);
echo "</pre>";
?>
Syntax
Parameter Values
Parameter Description
value Required. Specifies the value to use for filling the array
Syntax
array_fill_keys(keys, value)
Parameter Values
Parameter Description
value Required. Specifies the value to use for filling the array
<?php
$a = array("a","b","c","d","e");
echo "<pre>";
print_r($newArray);
echo "</pre>";
/* -----------Array Fill----------- */
echo "<pre>";
print_r($newArray1);
echo "</pre>";
?>
PHP Array_Walk()
The array_walk() function runs each array element in a user-defined function. The array's
keys and values are parameters in the function.
Syntax
Parameter Values
Parameter Description
array Required. Specifying an array
myfunction Required. The name of the user-defined function
parameter,.. Optional. Specifies a parameter to the user-defined function. You can assign one
. parameter to the function, or as many as you like
Return Value: Returns TRUE on success or FALSE on failure
Syntax
Parameter Values
Parameter Description
parameter,.. Optional. Specifies a parameter to the user-defined function. You can assign one
. parameter to the function, or as many as you like.
<?php
/* -------Array Walk-------*/
$fruits = array(
);
array_walk($fruits, "myFunction");
echo '<br><br>';
/* -------array_walk_recursive-------*/
$veggie,
);
?>
PHP Array_Map()
The array_map() function sends each value of an array to a user-made function, and
returns an array with new values, given by the user-made function.
Syntax
Parameter Values
Parameter Description
Return Returns an array containing the values of array1, after applying the user-made function to
Value: each one
<?php
/* -------Array Map-------*/
function square($n){
return $n * $n;
$a = [1, 2, 3, 4, 5];
echo "<pre>";
print_r($newArray);
echo "</pre>";
echo "<pre>";
print_r($newArray1);
echo "</pre>";
echo "<pre>";
print_r($newArray2);
echo "</pre>";
/* -------Passing no function-------*/
echo "<pre>";
print_r($newArray3);
echo "</pre>";
return strtoupper($n);
echo "<pre>";
print_r($newArray4);
echo "</pre>";
?>
PHP Array_Reduce()
The array_reduce() function sends the values in an array to a user-defined function, and
returns a string.
Syntax
Parameter Values
Parameter Description
<?php
/* -------Array Reduce-------*/
function myFunction($n,$m){
echo "<pre>";
print_r($newArray);
echo "</pre>";
echo "<pre>";
print_r($newArray1);
echo "</pre>";
//OR
$newArray2 = array_reduce($a, 'myFunction', 20);
echo "<pre>";
print_r($newArray2);
echo "</pre>";
echo "<pre>";
print_r($newArray3);
echo "</pre>";
//SUM
function myFunction1($n,$m){
return $n + $m;
print_r($newArray4);
echo "</pre>";
//Multiplication
function myFunction2($n,$m){
return $n * $m;
echo "<pre>";
print_r($newArray5);
echo "</pre>";
echo "<pre>";
print_r($newArray6);
echo "</pre>";
//Additon
function myFunction3($n,$m){
$n += $m;
return $n;
echo "<pre>";
print_r($newArray7);
echo "</pre>";
?>
The asort() function sorts an associative array in ascending order, according to the value.
Syntax
asort(array, sorttype)
Parameter Values
Parameter Description
array Required. Specifies the array to sort
sorttype Optional. Specifies how to compare the array elements/items. Possible values:
sort($food); //Sorting
echo "<pre>";
print_r($food);
echo "</pre>";
rsort($food); //Reverse
echo "<pre>";
print_r($food);
echo "</pre>";
$food1 = [22,15,3,64];
rsort($food1); //Reverse
echo "<pre>";
print_r($food1);
echo "</pre>";
);
echo "<pre>";
print_r($food2);
echo "</pre>";
);
echo "<pre>";
print_r($food3);
echo "</pre>";
arsort($food3);
echo "<pre>";
print_r($food3);
echo "</pre>";
/*-------Key Sort------- */
ksort($food3);
echo "<pre>";
print_r($food3);
echo "</pre>";
krsort($food3); // Key Reverse Sort
echo "<pre>";
print_r($food3);
echo "</pre>";
natsort($array1);
echo "<pre>";
print_r($array1);
echo "</pre>";
natcasesort($array2);
echo "<pre>";
print_r($array2);
echo "</pre>";
/*-------array_multisort --- not create new array------- */
$foods = array("orange","banana");
$veggie = array("lemon","carrot");
array_multisort($foods,$veggie);
echo "<pre>";
print_r($foods);
echo "</pre>";
echo "<pre>";
print_r($veggie);
echo "</pre>";
/*-------array_reverse------- */
$foods1 = array("orange","banana","apple","grapes");
$newArray = array_reverse($foods1);
echo "<pre>";
print_r($newArray);
echo "</pre>";
?>
next($food);
next($food);
prev($food);
end($food);
echo "<b>Current : </b>" . current($food) ."<br>";
echo "<b>Key : </b>" . key($food) ."<br><br>";
echo "<pre>";
print_r(each($food));
echo "</pre>";
?>
The PHP list( ) function is used to assign values to a list of variables in one operation. This
function was introduced in PHP 4.0.Syntax
Parameter
<?php
echo "<br><br>";
echo "<br><br>";
echo "<br><br>";
echo "<br><br>";
echo "<br><br>";
?>
The extract() function imports variables into the local symbol table from an array.
This function uses array keys as variable names and values as variable values. For each
element it will create a variable in the current symbol table.
Syntax
Parameter Values
Parameter Description
extract_rule Optional. The extract() function checks for invalid variable names and collisions with existing v
s names. This parameter specifies how invalid and colliding names are treated.
Possible values:
This parameter specifies the prefix. The prefix is automatically separated from the array key b
underscore character.
The compact() function creates an array from variables and their values.
Syntax
compact(var1, var2...)
Parameter Values
Parameter Description
var1 Required. Can be a string with the variable name, or an array of variables
Optional. Can be a string with the variable name, or an array of variables.
var2,...
Multiple parameters are allowed.
<?php
$color = array('a' => 'red', 'b' => 'green', 'c' => 'blue');
extract($color);
echo '<br><br>';
/*-------Extract_rules------- */
//EXTR_OVERWRITE
extract($color,EXTR_OVERWRITE);
echo '<br><br>';
//EXTR_SKIP
$a1 = "orange";
$color = array('a1' => 'red', 'b1' => 'green', 'c1' => 'blue');
extract($color,EXTR_SKIP);
echo '<br><br>';
//EXTR_PREFIX_SAME ;
extract($color,EXTR_PREFIX_SAME,"test");
echo '<br><br>';
//EXTR_PREFIX_ALL
extract($color,EXTR_PREFIX_ALL,"test");
echo '<br><br>';
/*-------Compact Function------- */
$firstname = "Yahoo";
$lastname = "Baba";
$age = "20";
$gender = "Male";
$country = "India";
echo '<pre>';
print_r($newArray);
echo '</pre>';
echo '<pre>';
print_r($newArray1);
echo '</pre>';
?>
PHP Array_Range
The PHP range( ) function is used to create an array containing a range of elements. The
PHP range( ) function returns an array of elements from low to high. This function was
introduced in PHP 4.0.
Syntax
Parameter
<?php
echo "<pre>";
print_r($newArray);
echo "</pre>";
/*-------Using step------- */
echo "<pre>";
print_r($newArray1);
echo "</pre>";
/*-------Using Alphabet------- */
echo "<pre>";
print_r($newArray2);
echo "</pre>";
//OR
echo "<pre>";
print_r($newArray3);
echo "</pre>";
/*-------Foreach Array Range Function------- */
?>