SlideShare a Scribd company logo
ARRAYS IN PHP
array();
three types of arrays:
• Indexed arrays - Arrays with numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one
or more arrays
PHP Indexed Arrays
• two ways to create indexed arrays:
$cars=array("Volvo","BMW","Toyota");
Or :
• $cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
EXAMPLE
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] .
".";
?>
Get The Length of an Array - The count() Function
used to return the length of an array:
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
• Associative arrays are arrays that use named keys that you
assign to them.
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
• The named keys can then be used in a script:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
•
Loop Through an Associative
Array
• use a foreach loop
Example
• <?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Multidimensional Arrays
• An array can also contain another array as a value, which in
turn can hold other arrays as well.
Example
<?php
// A two-dimensional array:
$cars = array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
• Output
• Is Megan a part of the Griffin family?
Array functions
Arrays in php
explode()
• Has 2 arguments the separator and source string
and returns an array.
echo $arr;
?>
implode()
• to reverse the process, joining the elements of an array into a
single string using user-supplied “glue.”
<?php
// define array
$arr = array('one', 'two', 'three', 'four');
// convert array to string
// output: 'one and two and three and four'
$str = implode(' and ', $arr);
echo $str;
?>
range()
• This function accepts two end points and returns an
array containing all the numbers between those end
points.
<?php
// define array
$arr = range(1,1000);
echo $arr;
?>
min() and max()
They accept an array of numbers and return the
smallest and largest values in the array respectively.
<?php
$arr = array(7, 36, 5, 48, 28, 90, 91, 3, 67, 42);
echo 'Minimum is ' . min($arr) . ' and maximum is ' .
max($arr);
?>
array_slice()
array_slice() function, which accepts three arguments: the original
array, the index position (offset) at which to start slicing, and
the number of elements to return from the starting offset.
<?php
$rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow‘,'orange', 'red');
// output: ('blue', 'green', 'yellow')
$arr = array_slice($rainbow, 2, 3);
echo $arr;
?>
• To extract a segment from the end of an array (rather than the
beginning), pass array_slice() a negative offset
• $arr = array_slice($rainbow, -5, 3);
Adding and Removing Array Elements
• array_unshift() function adds an element to the
beginning of an array;
• array_shift() function removes the first element of
an array;
• array_push() function adds an element to the end of
an array;
• array_pop() function removes the last element of
an array.
<?php
$movies = array('The Lion King', 'Cars', 'A Bug's Life');
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
// output: ('The Incredibles', 'Cars', 'Ratatouille')
echo $movies;
?>
Removing Duplicate Array Elements
• array_unique() function, which accepts an array and
returns a new array containing only unique values.
<?php
$duplicates = array('a', 'b', 'a', 'c', 'e', 'd', 'e');
// output: ('a', 'b', 'c', 'e', 'd')
$uniques = array_unique($duplicates);
echo $uniques;
?>
Randomizing and Reversing
Arrays
• shuffle() function re-arranges the elements of an array
in random order,
• array_reverse() function reverses the order of an array’s
elements.
<?php
$rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow‘,'orange', 'red');
// randomize array
shuffle($rainbow);
echo $rainbow;
// output: ('red', 'orange', 'yellow', 'green', 'blue‘, 'indigo', 'violet')
$arr = array_reverse($rainbow);
echo $arr;
?>
Searching Arrays
• in_array() function looks through an array for a
specified value and returns true if found.
<?php
// define array
$cities = array('London', 'Paris', 'Barcelona', 'Lisbon', 'Zurich');
// search array for value
echo in_array('Barcelona', $cities);
?>
• the array_key_exists() function looks for a match to
the specified search term among an array’s key
<?php
$cities = array("United Kingdom" => "London",
"United States" => "Washington",
"France" => "Paris“,"India" => "Delhi”);
// search array for key
echo array_key_exists('India', $cities);
?>
Sorting an array
• sort() function, which lets you sort numerically
indexed arrays alphabetically or numerically, from
lowest to highest value.
<?php
$data = array(15,81,14,74,2);
// output: (2,14,15,74,81)
sort($data);
echo $data;
?>
• asort() function, which maintains the correlation
between keys and values while sorting.
<?php
$profile = array("fname" => "Susan“,"lname" =>
"Doe“,"sex" => "female“,"sector" => "Asset
Management“ );
// output: ('sector' => 'Asset Management‘, 'lname' => 'Doe‘, 'fname' => 'Susan‘, 'sex' =>
'female')
asort($profile);
echo $profile;
?>
• ksort() function, which uses keys instead of
values when performing the sorting.
$profile = array("fname" => "Susan“,"lname" => "Doe",
"sex" => "female“,"sector" => "Asset Management”);
// output: ('fname' => 'Susan‘, 'lname' => 'Doe‘,'sector' => 'Asset Management‘, 'sex' =>
'female')
ksort($profile);
echo $profile;
?>
• To reverse the sorted sequence generated by sort(), asort(),
and ksort(), use the rsort(), arsort(), and krsort() functions
respectively.
Merging Arrays
• merge one array into another with its array_merge()
function, which accepts one or more array variables
<?php
$dark = array('black', 'brown', 'blue');
$light = array('white', 'silver', 'yellow');
// output: ('black', 'brown', 'blue‘, 'white', 'silver', 'yellow')
$colors = array_merge($dark, $light);
echo $colors;
?>
Comparing Arrays
• the array_intersect() function returns the values
common to two arrays
• array_diff() function returns the values from the first
array that don’t exist in the second.
<?php
$orange = array('red', 'yellow');
$green = array('yellow', 'blue');
// output: ('yellow')
$common = array_intersect($orange, $green);
echo $common;
// find elements in first array but not in second
// output: ('red')
$unique = array_diff($orange, $green);
echo $unique;
?>
PHP list() Function
• The list() function is used to assign values to a list of
variables in one operation.
• Syntax
list(var1, var2, ...)
• Example :
• <?php
$my_array = array("Dog","Cat","Horse");
list($a, , $c) = $my_array;
echo "Here I only use the $a and $c variables.";
?>

More Related Content

PPTX
Functions in PHP.pptx
PPTX
Form Handling using PHP
PPTX
Operators php
PDF
Remote Method Invocation (RMI)
PPT
Php with MYSQL Database
PPTX
Php string function
PPTX
Remote Method Innovation (RMI) In JAVA
Functions in PHP.pptx
Form Handling using PHP
Operators php
Remote Method Invocation (RMI)
Php with MYSQL Database
Php string function
Remote Method Innovation (RMI) In JAVA

What's hot (20)

PDF
Remote Method Invocation in JAVA
PPT
Class 5 - PHP Strings
PPT
Java Socket Programming
PPTX
Method overloading
PPTX
Php.ppt
PDF
Php introduction
PPTX
Statements and Conditions in PHP
PPT
SQLITE Android
PPTX
Lesson 6 php if...else...elseif statements
PPTX
Introduction to php
PPT
Input and output in C++
PPTX
Java RMI
PDF
Java data types, variables and jvm
PPTX
Polymorphism presentation in java
PPT
PHP - Introduction to File Handling with PHP
PPTX
Document Object Model (DOM)
PPT
Java Networking
PPTX
Lecture_7-Encapsulation in Java.pptx
PPT
PHP - Introduction to PHP Forms
PDF
jQuery - Chapter 3 - Effects
Remote Method Invocation in JAVA
Class 5 - PHP Strings
Java Socket Programming
Method overloading
Php.ppt
Php introduction
Statements and Conditions in PHP
SQLITE Android
Lesson 6 php if...else...elseif statements
Introduction to php
Input and output in C++
Java RMI
Java data types, variables and jvm
Polymorphism presentation in java
PHP - Introduction to File Handling with PHP
Document Object Model (DOM)
Java Networking
Lecture_7-Encapsulation in Java.pptx
PHP - Introduction to PHP Forms
jQuery - Chapter 3 - Effects
Ad

Similar to Arrays in php (20)

PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
PPTX
UNIT IV (4).pptx
PPTX
PHP array 1
PPTX
Chapter 2 wbp.pptx
PPT
Class 4 - PHP Arrays
PPT
PHP array 2
PPTX
PHP Array Functions.pptx
PPTX
Array functions for all languages prog.pptx
PPTX
Array functions using php programming language.pptx
PPT
Using arrays with PHP for forms and storing information
PPTX
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
PPT
Php Chapter 2 3 Training
PPTX
Unit 2-Arrays.pptx
PPTX
Web Application Development using PHP Chapter 4
PDF
Array String - Web Programming
PPTX
PHP Functions & Arrays
PPTX
5 Arry in PHP.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
PPT
PHP - Introduction to PHP Arrays
PPT
Php my sql - functions - arrays - tutorial - programmerblog.net
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
UNIT IV (4).pptx
PHP array 1
Chapter 2 wbp.pptx
Class 4 - PHP Arrays
PHP array 2
PHP Array Functions.pptx
Array functions for all languages prog.pptx
Array functions using php programming language.pptx
Using arrays with PHP for forms and storing information
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Php Chapter 2 3 Training
Unit 2-Arrays.pptx
Web Application Development using PHP Chapter 4
Array String - Web Programming
PHP Functions & Arrays
5 Arry in PHP.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
PHP - Introduction to PHP Arrays
Php my sql - functions - arrays - tutorial - programmerblog.net
Ad

Recently uploaded (20)

PDF
Formation of Supersonic Turbulence in the Primordial Star-forming Cloud
PPT
POSITIONING IN OPERATION THEATRE ROOM.ppt
PPTX
Derivatives of integument scales, beaks, horns,.pptx
PDF
An interstellar mission to test astrophysical black holes
PPTX
BIOMOLECULES PPT........................
PDF
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
PPTX
neck nodes and dissection types and lymph nodes levels
PDF
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
PPTX
Taita Taveta Laboratory Technician Workshop Presentation.pptx
PPTX
EPIDURAL ANESTHESIA ANATOMY AND PHYSIOLOGY.pptx
PDF
Biophysics 2.pdffffffffffffffffffffffffff
PDF
. Radiology Case Scenariosssssssssssssss
PDF
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
PDF
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
PPTX
famous lake in india and its disturibution and importance
PDF
Phytochemical Investigation of Miliusa longipes.pdf
PPTX
Cell Membrane: Structure, Composition & Functions
PDF
Placing the Near-Earth Object Impact Probability in Context
PPTX
2. Earth - The Living Planet earth and life
PPTX
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
Formation of Supersonic Turbulence in the Primordial Star-forming Cloud
POSITIONING IN OPERATION THEATRE ROOM.ppt
Derivatives of integument scales, beaks, horns,.pptx
An interstellar mission to test astrophysical black holes
BIOMOLECULES PPT........................
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
neck nodes and dissection types and lymph nodes levels
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
Taita Taveta Laboratory Technician Workshop Presentation.pptx
EPIDURAL ANESTHESIA ANATOMY AND PHYSIOLOGY.pptx
Biophysics 2.pdffffffffffffffffffffffffff
. Radiology Case Scenariosssssssssssssss
Mastering Bioreactors and Media Sterilization: A Complete Guide to Sterile Fe...
CAPERS-LRD-z9:AGas-enshroudedLittleRedDotHostingaBroad-lineActive GalacticNuc...
famous lake in india and its disturibution and importance
Phytochemical Investigation of Miliusa longipes.pdf
Cell Membrane: Structure, Composition & Functions
Placing the Near-Earth Object Impact Probability in Context
2. Earth - The Living Planet earth and life
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5

Arrays in php

  • 2. array(); three types of arrays: • Indexed arrays - Arrays with numeric index • Associative arrays - Arrays with named keys • Multidimensional arrays - Arrays containing one or more arrays
  • 3. PHP Indexed Arrays • two ways to create indexed arrays: $cars=array("Volvo","BMW","Toyota"); Or : • $cars[0]="Volvo"; $cars[1]="BMW"; $cars[2]="Toyota";
  • 4. EXAMPLE <?php $cars=array("Volvo","BMW","Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?>
  • 5. Get The Length of an Array - The count() Function used to return the length of an array: <?php $cars=array("Volvo","BMW","Toyota"); echo count($cars); ?>
  • 6. Loop Through an Indexed Array <?php $cars=array("Volvo","BMW","Toyota"); $arrlength=count($cars); for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo "<br>"; } ?>
  • 7. PHP Associative Arrays • Associative arrays are arrays that use named keys that you assign to them. $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); or: $age['Peter']="35"; $age['Ben']="37"; $age['Joe']="43"; • The named keys can then be used in a script: Example <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> •
  • 8. Loop Through an Associative Array • use a foreach loop Example • <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?>
  • 9. Multidimensional Arrays • An array can also contain another array as a value, which in turn can hold other arrays as well. Example <?php // A two-dimensional array: $cars = array ( array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100) ); ?>
  • 11. Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )
  • 12. echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; • Output • Is Megan a part of the Griffin family?
  • 15. explode() • Has 2 arguments the separator and source string and returns an array. echo $arr; ?>
  • 16. implode() • to reverse the process, joining the elements of an array into a single string using user-supplied “glue.” <?php // define array $arr = array('one', 'two', 'three', 'four'); // convert array to string // output: 'one and two and three and four' $str = implode(' and ', $arr); echo $str; ?>
  • 17. range() • This function accepts two end points and returns an array containing all the numbers between those end points. <?php // define array $arr = range(1,1000); echo $arr; ?>
  • 18. min() and max() They accept an array of numbers and return the smallest and largest values in the array respectively. <?php $arr = array(7, 36, 5, 48, 28, 90, 91, 3, 67, 42); echo 'Minimum is ' . min($arr) . ' and maximum is ' . max($arr); ?>
  • 19. array_slice() array_slice() function, which accepts three arguments: the original array, the index position (offset) at which to start slicing, and the number of elements to return from the starting offset. <?php $rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow‘,'orange', 'red'); // output: ('blue', 'green', 'yellow') $arr = array_slice($rainbow, 2, 3); echo $arr; ?> • To extract a segment from the end of an array (rather than the beginning), pass array_slice() a negative offset • $arr = array_slice($rainbow, -5, 3);
  • 20. Adding and Removing Array Elements • array_unshift() function adds an element to the beginning of an array; • array_shift() function removes the first element of an array; • array_push() function adds an element to the end of an array; • array_pop() function removes the last element of an array.
  • 21. <?php $movies = array('The Lion King', 'Cars', 'A Bug's Life'); // remove element from beginning of array array_shift($movies); // remove element from end of array array_pop($movies); // add element to end of array array_push($movies, 'Ratatouille'); // add element to beginning of array array_unshift($movies, 'The Incredibles'); // print array // output: ('The Incredibles', 'Cars', 'Ratatouille') echo $movies; ?>
  • 22. Removing Duplicate Array Elements • array_unique() function, which accepts an array and returns a new array containing only unique values. <?php $duplicates = array('a', 'b', 'a', 'c', 'e', 'd', 'e'); // output: ('a', 'b', 'c', 'e', 'd') $uniques = array_unique($duplicates); echo $uniques; ?>
  • 23. Randomizing and Reversing Arrays • shuffle() function re-arranges the elements of an array in random order, • array_reverse() function reverses the order of an array’s elements. <?php $rainbow = array('violet', 'indigo', 'blue', 'green', 'yellow‘,'orange', 'red'); // randomize array shuffle($rainbow); echo $rainbow; // output: ('red', 'orange', 'yellow', 'green', 'blue‘, 'indigo', 'violet') $arr = array_reverse($rainbow); echo $arr; ?>
  • 24. Searching Arrays • in_array() function looks through an array for a specified value and returns true if found. <?php // define array $cities = array('London', 'Paris', 'Barcelona', 'Lisbon', 'Zurich'); // search array for value echo in_array('Barcelona', $cities); ?>
  • 25. • the array_key_exists() function looks for a match to the specified search term among an array’s key <?php $cities = array("United Kingdom" => "London", "United States" => "Washington", "France" => "Paris“,"India" => "Delhi”); // search array for key echo array_key_exists('India', $cities); ?>
  • 26. Sorting an array • sort() function, which lets you sort numerically indexed arrays alphabetically or numerically, from lowest to highest value. <?php $data = array(15,81,14,74,2); // output: (2,14,15,74,81) sort($data); echo $data; ?>
  • 27. • asort() function, which maintains the correlation between keys and values while sorting. <?php $profile = array("fname" => "Susan“,"lname" => "Doe“,"sex" => "female“,"sector" => "Asset Management“ ); // output: ('sector' => 'Asset Management‘, 'lname' => 'Doe‘, 'fname' => 'Susan‘, 'sex' => 'female') asort($profile); echo $profile; ?>
  • 28. • ksort() function, which uses keys instead of values when performing the sorting. $profile = array("fname" => "Susan“,"lname" => "Doe", "sex" => "female“,"sector" => "Asset Management”); // output: ('fname' => 'Susan‘, 'lname' => 'Doe‘,'sector' => 'Asset Management‘, 'sex' => 'female') ksort($profile); echo $profile; ?> • To reverse the sorted sequence generated by sort(), asort(), and ksort(), use the rsort(), arsort(), and krsort() functions respectively.
  • 29. Merging Arrays • merge one array into another with its array_merge() function, which accepts one or more array variables <?php $dark = array('black', 'brown', 'blue'); $light = array('white', 'silver', 'yellow'); // output: ('black', 'brown', 'blue‘, 'white', 'silver', 'yellow') $colors = array_merge($dark, $light); echo $colors; ?>
  • 30. Comparing Arrays • the array_intersect() function returns the values common to two arrays • array_diff() function returns the values from the first array that don’t exist in the second. <?php $orange = array('red', 'yellow'); $green = array('yellow', 'blue'); // output: ('yellow') $common = array_intersect($orange, $green); echo $common; // find elements in first array but not in second // output: ('red') $unique = array_diff($orange, $green); echo $unique; ?>
  • 31. PHP list() Function • The list() function is used to assign values to a list of variables in one operation. • Syntax list(var1, var2, ...) • Example : • <?php $my_array = array("Dog","Cat","Horse"); list($a, , $c) = $my_array; echo "Here I only use the $a and $c variables."; ?>