Arrays in PHP
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.
There are 3 types of array
Indexed Arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or
more arrays
Arrays in PHP
Array items can be of any data type
type.
The most common are strings and numbers ((int,
float), but array items can also be objects, functions or
even arrays.
You can have different data types in the same array.
array
Arrays in PHP
We can create arrays by using the array() function:
$mobile= array(“samsung",
", ““nokia", “oneplus");
You can also use a shorter syntax by using
the [] brackets:
$mobile = [“samsung", “nokia
nokia", “oneplus“];
Array Keys
When creating indexed arrays the keys are given
automatically, starting at 0 and increased by 1 for each
item, so the array could also be created with keys
keys:
$mobile= [ 0 => “samsung",
", 1 => “nokia",
2 =>“oneplus" ];
Access Array items
To access an array item, you can refer to the index
number for indexed arrays, and the key name for
associative arrays.
$mobile= array(“samsung",
", “nokia",
“ “oneplus");
echo $mobile[0];
echo $mobile[1];
The first item always has index value as zero.
Update/Change Array items
To update an existing array item, you can refer to the
index number for indexed arrays, and the key name
for associative arrays.
$mobile= array(“samsung",
", “nokia",
“ “oneplus");
echo $mobile[1];
$mobile[1]=“motorola”;”;
echo $mobile[1];
foreach loop
$mobile= array(“samsung", “nokia", “oneplus");
foreach( $mobile as $x)
{
echo “$x”;
echo “<br>”;
}
The foreach loop - Loops through a block of code for
each element in an array
count function
The count() function returns the number of elements in
an array.
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Display array using for loop
$mobile= array("samsung", "nokia", "oneplus");
for($n=0; $n<count($mobile); $n++)
{
echo "$mobile[$n]";
echo "<br>";
}
Display array elements
<?php
$mobile= array("samsung", "nokia", "oneplus");
echo "<pre>";
var_dump($mobile);
print_r($mobile);
echo "</pre>";
?>
The print_r()() function prints the information about a
variable in a more human-readable
readable way
PHP Associative arrays
Associative arrays are arrays that use named keys that
you assign to them.
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
var_dump($car);
?>
Access Associative arrays
To access an array item you can refer to the key name
name.
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
echo $car["model"];
Change Value
To change the value of an array item, use the key
name:
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
$car["year"] = 2024;
var_dump($car);
Foreach loop
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
foreach ($car as $x => $y)
{
echo "$x: $y <br>";
}
array_flip() function in PHP
It will flip all the keys with their associated values in an array
array:
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
echo "<pre>";
print_r($car);
$car=array_flip($car);
print_r($car);
echo "</pre>";
Multidimensional arrays
A multidimensional array is an array containing one or
more arrays.
Consider a table: (3 rows and 3 columns)
Abc 10 20
Pqr 55 65
Xyz 67 97
Multidimensional arrays
Abc 10 20
Pqr 55 65
Xyz 67 97
$value = array (
array ("Abc","10","20"),
array ("Pqr","55","65"),
array ("Xyz","67","97")
);
<?php
$value = array (
array ("Abc","10","20"),
array ("Pqr","55","65"),
array ("Xyz","67","97")
);
echo $value[0][0].' '.$value[0][1].''.$value[0][2];
echo $value[1][0].''.$value[1][1].''.$value[1][2];
echo $value[2][0].''.$value[2][1].''.$value[2][2];
echo "<pre>";
var_dump($value);
print_r($value);
echo "</pre>";
?>
Using for loop
for ($r=0; $r<3 ; $r++)
{
for($c=0; $c<3 ; $c++)
{
echo $value[$r][$c];
}
echo "<br>";
}
Using foreach loop
foreach ($value as $v1)
{
foreach ($v1 as $v2)
{
echo "$v2 ";
}
echo "<br>";
}
Program to find sum of array elements
<?php
$value = array(10,20,30);
$sum=0;
for($i=0; $i<count($value); $i++)
{
$sum=$sum + $value[$i];
}
echo "Sum of array elements is $sum";
?>
Sorting functions
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order,
according to the value
ksort() - sort associative arrays in ascending order,
according to the key
arsort() - sort associative arrays in descending order,
according to the value
krsort() - sort associative arrays in descending order,
according to the key
<?php
$value = array(67,10,5,98);
echo "<pre>";
print_r($value);
sort($value);
print_r($value);
echo "</pre>";
?>
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang",
"color"=>"black");
echo "<pre>";
print_r($car);
krsort($car);
print_r($car);
echo "</pre>";
?>
PHP explode() Function
The explode() function breaks a string into an array
array.
Syntax
explode(separator,
separator, string, limit)
limit
Where limit is optional. It specifies
pecifies the number of array
elements to return.
PHP explode() Function
<?php
$input="abc,def,ghi,jkl";
$output=explode("," , $input );
echo "<pre>";
print_r($output);
echo "</pre>";
//print_r(explode("," ,$input ));
?>
PHP implode() Function
The implode() function returns a string from the
elements of an array.
Syntax
implode(separator,array
separator,array)
The separator parameter of implode() is optional
and by default it is an empty string.
PHP implode() Function
<?php
$input=array("abc","def","ghi","jkl");
$output=implode(" ",$input);
echo "$output";
?>
PHP string Functions
strlen() Function
: This function takes a string as argument
and returns and integer value representing
the length of string. It calculates the length
of the string including all the whitespaces
and special characters.
Syntax: strlen( $string )
PHP string Functions
str_word_count()
() Function
: The str_word_count()
() function counts the
number of words in a string.
string
strrev() Function
: The strrev()
() function reverses a string.
string
PHP string Functions
strtoupper() Function
:The strtoupper()
() function takes a string as
argument and returns the string with all
characters in Upper Case.
Case
strtolower()() Function
:This
This function takes a string as argument ans
returns the string with all of the characters in
Lower Case.
PHP string Functions
ucwords()
() Function
This function takes a string as argument and
returns the string with the first character of
every word in Upper Case and all other
characters remains unchanged.
unchanged
PHP string Functions
strpos() Function:
This function helps us to find the position of
the first occurrence of a string in another
string. This returns an integer value of the
position of the first occurrence of the string.
This function is case-sensitive
sensitive.
Syntax: strpos(original_str
original_str, search_str,
start_pos);
PHP string Functions
str_replace()
() Function
The str_replace()
() function replaces some
characters with some other characters in a
string.
Syntax:
str_replace(find,replace,string,count
find,replace,string,count)
Count is optional
PHP string Functions
strcmp() Function
The strcmp() () function compares two strings
strings.
It is case sensitive.
PHP Functions
PHP has more than 1000 built
built-in functions, and
in addition you can create your own custom
functions / user defined functions.
A function is a block of statements that can be
used repeatedly in a program.
A function will not execute automatically.
A function will be executed by a call to the
function.
Create a user defined Function
A user-defined
defined function declaration starts with
the keyword function, followed by the name of
the function:
function hello()
{
echo “hello”;
}
Call a user defined Function
To call the function, just write its name followed
by parentheses ()
function hello()
{
echo “hello world”;
}
hello();
hello();
Function parameters/Arguments
Information can be passed to functions through
arguments. An argument is just like a variable
variable.
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.
Function parameters/Arguments
function display( $x )
{
echo “value is $x”;
}
display(10);
display(20);
Default parameters/Arguments
function display( $x=20 )
{
echo “value is $x”;
}
display(); //it will use default value as 20
display(50);
Function with return values
function input( $x )
{
return $x;
}
$value= input(40);
echo $value;
//echo input(50);
Function with return values
function sum( $x, $y )
{
$z=$x+$y;
return $z;
}
$value= sum(40,50)
echo $value;
In this examples, the function is called by passing
values of variables.
Call by reference
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:
Call by reference
function input(&$x)
{
$x=$x+10;
}
$n=10;
echo $n; //it will print 10
input($n);
echo $n; //it will print 20
Pass an array as an parameter
<?php
$value=array(10,20,30);
function sum($x)
{
$sum=0;
foreach($x as $y)
{
$sum= $sum + $y;
}
echo "sum is $sum";
}
sum($value);
?>
Scope of variables (global / local)
<?php
$x=10;
function test()
{
global $x;
echo "<br>inside a function $x";
}
test ();
echo "<br>outside a function $x";
?>
Practice Programs
Write php program to find greatest of two
numbers using user defined function.
Write php program to check a given number is
even or odd using user defined function.
Write php program to find a given number is
prime or not using user defined function
Anonymous function in php
an anonymous function is a function that
doesn’t have any name specified at the time of
definition. Such a function is also
called closure or lambda function
function.
$anonymousFunction = function($arg1, $arg2, ...) {
// Function body
};
Anonymous function in php
// Define and use an anonymous function
$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);
Anonymous function in php
Note that there is no function name between
the function keyword and the opening
parenthesis, and the fact that there is a semicolon
after the function definition.
This implies that anonymous function definitions
are expressions. When assigned to a variable, the
anonymous function can be called later using the
variable’s name.
Iterators in php
Every PHP array keep track of current element.
The pointer to the current element is known as
Iterator.
current()
reset()
next()
prev()
end()
Key()
pos()
$choice=array("CO","EE","ET","CE","ME");
echo current($choice)."<br>";
echo next($choice)."<br>";
echo prev($choice)."<br>";
echo end($choice)."<br>";
echo reset($choice)."<br>";
echo key($choice)."<br>";
echo pos($choice)."<br>";
echo next($choice)."<br>";
echo pos($choice)."<br>";
<?php
$input="Govt poly khamgaon";
$op=explode(" ",$input);
$c=count($op);
echo "number of words = $c";
?>
<?php
$im=imagecreate(500,500);
imagecolorallocate($im,0,0,100);
$c=imagecolorallocate($im,255,255,255);
imagestring($im,5,200,0,"GP Khamgaon",$c);
imagefilledrectangle($im, 40, 90,450 , 25, $c);
header("Content-Type:
Type: image/png");
imagepng($im);
imagedestroy($im);
?>
Basics graphics in php
imagecreate(( $width, $height )
used to create a new image.
In general imagecreatetruecolor()
imagecreatetruecolor function is
used instead of imagecreate()
imagecreate function
because imagecreatetruecolor()
imagecreatetruecolor function creates
high quality images.
Basics graphics in php
imagecolorallocate ( $image, $red, $green, $blue);
imagestring( $image, $font, $x, $y, $string, $color )
The imagepng() function is an inbuilt function
in PHP which is used to display image to browser
or file
Pdf files in php
FPDF is a class used to create pdf files in php.
Use fpdf.org to download this.
Use require() function to include fpdf.php file
require("fpdf.php");
Pdf files in php
Create object of FPDF
$pdf= new FPDF(); //memory allocation to object
Call or invoke various methods/functions provided
by FPDF class/library by using created object $pdf
To add a page, $pdf->AddPage();
>AddPage();
Pdf files in php
SetFont() method is used to set the font, style, and
size of the text that is added to a PDF using
the Cell() method.
The first parameter sets the font family, the second
parameter sets the font style, and the third
parameter sets the font size.
size
$pdf->SetFont('Arial','UIB',
'UIB',20);
$pdf->cell(80,10,"GP Khamgaon");
Khamgaon
//x and y coordinages along with text in cell()
method
Pdf files in php
Use output() method to get the output
It may takes two parameters
Ex: pdf->output(“filename”,
>output(“filename”, “mode I/D”);
D mode will download the pdf file automatically
in the browser
Pdf files in php
<?php
require("fpdf.php");
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetTextColor(255,0,0);
>SetTextColor(255,0,0);
$pdf->SetFont('Arial','UIB',20);
>SetFont('Arial','UIB',20);
$pdf->cell(80,10,"GP
>cell(80,10,"GP Khamgaon");
$pdf->output();
?>
THANK YOU