Array is a special variable which can store multiple value. ( Note : a normal variable can store only one value at a time ). Arrays are the oldest and most important data structure which can hold multiple values. Each value in an array is associated with a key. And we can retrieve each value from array using the keys.
Arrays can be mainly two types
- One-dimensional arrays
- Multidimensional arrays
Array in PHP can be categorized as
- Numeric arrays
- Associative array
- Multidimensional array
In PHP array can be declared using the construct array()
Numeric arrays are with a numeric index. Here we don’t need specify the keys. Index will start from 0. Means first data can be accessed using the index 0 , second data can be accessed using the index 1 etc
See the Example for a numeric array declaration
Its same as the following declarations
In Associative arrays each key is associated with a value.Here we need to specify each key and its associated value. And these values can be fetched using the declared keys.
See the example of an Associative array declaration
$age = array(“Syam”=>30, “Binu”=>25, “Bob”=>50, “cathy”=>30);
Here Syam, Binu etc are the keys and values are associated with those keys using => .
In this example we are trying to store the ages of some persons using arrays. So if we want to know the age of one particular person , we only need to know his name ( key ).
The above array can be declared same as
In Multidimensional arrays each element in array can be another array. Its useful for building matrices, tree and table like data storage structures.In some programming scenarios we can avoid the usage of several different one-dimensional arrays using a single Multidimensional arrays for our programming optimization , speed and other things.
For example , consider a case we need to store names , age and location. We can use a multidimensional array. See below
Here is a sample program of array in PHP ( using the above array )
<?php $data=array ("Syam"=>array("age"=>30,"location"=>"India"),"Bob"=>array("age"=>50,"location"=>"USA") ); echo $data["Bob"]["location"]; ?>
Its output will be ;