An array is a kind of special variable having more than one value which shares same name but different index or id.

What is an array in PHP?

An array in PHP is actually an ordered map. A map is type that maps or associates values to keys. This type is optimized in several ways so you can use it as a real array, or a list (vector) , hash table, dictionary, collection, stack, queue and tree.

An array can be created with array() function and takes certain number of comma separated key=> value pairs. This key may be either an integer or a string.

Three types are there in PHP array:

  • Indexed Array :  Numeric Index
  • Associative Array  : String Index
  • Multidimensional Array

 1. Indexed Array in PHP :

Example :

<?php
 $str = array('DELHI' , 'MUMBAI', 'BANGLORE');
 $str[3] ='AHEMDABAD';
 foreach( $str as $Val)
 {
 echo "<br>", $Val;
 }
 echo "<br>-------------------";
$num = array(10,11,12,13,14);
 foreach( $num as $Val)
 {
 echo "<br>", $Val;
 }
 ?>

PHP Indexed Array
2. Associative Array in PHP:

Example :

<?php
 $age = array ('A' => 20 , 'B'=> 21 , 'C'=> 25);
 echo $age['A'] ,"<br>";
 echo $age['B'],"<br>";
$arr = array('Name' => 'ABC' , 20 =>'Age' , 10 => true);
 echo $arr['Name'] ,"<br>";       // ABC
 echo $arr[12],"<br>";                // Age
 echo $arr[10];                //1
 ?>

Associative Array in PHP
3. Multidimensional Array in PHP :

Example :

<?php
 $A = array ('B' => array(6=>5 , 13=>9, 'c' => 42));
 echo $A['B'][6];    //5
 echo "<br>" , $A['B'][13];  //9
 echo "<br>" , $A['B']['c'];   //42
 ?>

Multidimensional array in PHP

  • If you don’t specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
  • Example :
array(5=> 40 , 34, 76 , 'b' =>10);

is same as

array(5=> 40, 6=> 34, 7=> 76, 'b'=>10);
  • Using TRUE as a key will evaluate to integer 1 as  key. Using FALSE as a key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string.