What is an Array?

You have already learnt that a variable is a storage area holding numbers and text. The problem is, a variable will hold only one value.
An array is a special variable, which can hold more than one value, at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Benz";
$cars2="Ford";
$cars3="BMW";
In PHP, there are three kind of arrays:
  • Numeric array - An array with a numeric index
  • Associative array - An array where each ID key is associated with a value
  • Multidimensional array - An array containing one or more arrays

Numeric Arrays

A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Benz","Volvo","BMW","Toyota");
2. In the following example we assign the index manually:
$cars[0]="Benz";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
<?php
$cars[0]="Benz";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Luxury cars.";
?>

Click to see output

Associative Arrays

An associative array, each ID key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
$ages = array("Ashok"=>32, "Kartikeya"=>30, "Razi"=>34);
Or
<?php
$ages['Ashok'] = "32";
$ages['Kartikeya'] = "30";
$ages['Razi'] = "34";

echo "Razi is " . $ages['Ashok'] . " years old.";
?>

Click to see output

Multidimensional Arrays

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Nielsen"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Nielsen] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Example2
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?"

Click to see output