You are on page 1of 7

Array

ETL LABS PVT LTD – PHP 68


Arrays
Arrays are complex variables that allow us to
store more than one value or a group of values
under a single variable name. Let's suppose 1
you want to store cars in your PHP script.
Storing the cars one by one in a variable could
look something like this:

ETL LABS PVT LTD – PHP 69


Types of Array

Type 1 Type 2 Type 3

Indexed Associative Multidimensional


array array array
An array with a An array where each key An array containing one or
numeric key. has its own specific value. more arrays within itself.

ETL LABS PVT LTD – PHP 70


Indexed Array
There are two ways to create indexed arrays:

<?php
The index can be assigned automatically
$cars
(index always starts at 0), like this:
= array("Volvo", "BMW", "Toyota
");
3 $cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ",
" . $cars[1] . " and " .
$cars[2] . "."; or the index can be assigned manually:
?>
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

ETL LABS PVT LTD – PHP 71


Associative array
Associative arrays are arrays that use named
keys that you assign to them.
<?php
There are two ways to create an associative $age = array("Peter"=>"35",
array: "Ben"=>"37", "Joe"=>"43");
4 echo "Peter is " .
$age = array("Peter"=>"35", "Ben"=>"37", $age['Peter'] . " years
"Joe"=>"43"); old.";?>
or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

ETL LABS PVT LTD – PHP 72


Multidimensional array

A multidimensional array
is an array containing one
or more arrays.

PHP understands
multidimensional arrays
that are two, three, four,
five, or more levels deep.

ETL LABS PVT LTD – PHP 73


Tabular representation of two dimensional array

We can store the data from the table above in a


0 1 2 two-dimensional array, like this:

Name Stock Sold


$cars = array
0 Volvo 22 18 (
array("Volvo",22,18),
1 BMW 15 13 array("BMW",15,13),
2 Saab 5 2 array("Saab",5,2),
array("Land Rover",17,15)
3 Land Rover 17 15 );
Now the two-dimensional $cars array contains four
arrays, and it has two indices: row and column.

To get access to the elements of the $cars array


we must point to the two indices (row and column)

ETL LABS PVT LTD – PHP 74