PHP Arrays

What is an arrays in PHP ?

An array is a data structure set of elements that store multiple values in a single variable on the pair basis of key/value

An array is a compound types data type, it is hold more than one value at a time

$name1 ='Vishal Gupta';
$name2 ='Vipin Katiyar';
$name3 ='Harshendra';

Supposed you have 1000 names then it is not good solution to create 1000 variables, we have to create an array

$name =array('name1'=>'Vishal Gupta','name2'=>'Vipin Katiyar','name3' =>'Harshendra');
echo $name['name1'];
//output : Vishal Gupta

Create an Array in PHP

array() function to used create an array


Types of Arrays in PHP ?

There are three types of arrays in PHP. These are:

  • Indexed array - Array with neumric key
  • Associative array - Array with named keys means array with key and it's specific value
  • Multidimensional array - An array conatining one more array

Indexed or numeric array

In Indexed array each elements with a numric key

Note:In an indexed array, index always starts with 0.
//Indexed array syntax
//Indexed assigned automatically
$lang = array('PHP','Java','C#');


//Indexed assigned manually

Associative array

Associative arrays is like indexed array, but Index can be of any data type. data stored at key,value pair.

//Associative array syntax
$user_qualification = array("Vishal"=>'MCA','Vipin'=>'','Harsh'=>'MBA');



Multidimensional array

In Multidimensional array is an array of arrays, in which each element can be also an array. Example : 2D,3D (an array of arrays of arrays.), etc

//Multidimensional array syntax
$users = array(

echo $users[0]['name'];
//Output :: Pradeep

How to get the length of array in PHP ?

You get the length of the array by using count()

$users = array(

echo count($users); //2
echo count($users,1); //6

Array viewing data

By using print_r() or var_dump() view the array elements.

$users = array(

print_r() for view the array data

Array ( [0] => Array ( [name] => Pradeep [email] => ) [1] => Array ( [name] => Rahul [email] => ) )

var_dump() for view the array data

array (size=2)
  0 => 
    array (size=2)
      'name' => string 'Pradeep' (length=7)
      'email' => string '' (length=15)
  1 => 
    array (size=2)
      'name' => string 'Rahul' (length=5)
      'email' => string '' (length=15)