PHP Arrays

  1. An array is a concept of declaring a variable in which multiple values can be stored or
    An array stores multiple values in a single variable..
  2. an array in PHP is compound type.
  3. An array is actually an ordered map.
    A map is a type that maps values.
  4. Each element in array has its own index.
  5. It takes a certain number of comma separated Key =>value pairs
    Array(key=>value, key=>value, . . .)


  1. It is a function of PHP used to get the size of an array
  2. The size of an array is number of elements present in the array

Ex: count($x)

Print_r (array_name)

It is Function used to display the entire content of array with key.


We have 3 types of arrays in PHP

  1. Numeric array
  2. Associative array
  3. array

Numeric Array

Numeric stores the each array element with a numeric index.

In PHP we have 2 techniques to create a array.

  1. Assign index automatically
    $x = array(10,20,30,40)
  2. Assign index Manually
    $x = array();

Loops in arrays

Foreach loop:-

  1. For each loop gives an easy way to iterate over arrays.
  2. foreach works only on arrays and objects.

Syntax 1 of foreach :-

foreach (array as $value)


for every iteration the value of current array element is assigned to $value and the array  pointer is moved to next element so on ..
On the next loop iteration it will be looking at next array value.

Syntax2 for foreach loop

foreach (array as $key=> value)
This loop is also does the same thing , but except that the current elements key index will be assigned to the variable $key on each loop iteration.

<? PHP
Echo “size of array is “.count($x).”<br>”;
echo”size of array is “.count($y).”<br>”;
foreach($x as $k=>$R)

Associative Array

  1. An array where each ID key is associated with a value is called assosiative array
  2. With assosiative arrays we can use the values as keys and assign values to them.
  3. when storing data about specific named values, a numerical array is not always the best way to do it.

Example :-

  1. $Ages = array(“x”=>20, “y”=>30, “z”=>40);

  2. $ages = array();
    $ages[“x”] = 20;
    $ages[“y”] = 30;
    $ages[“z”] = 40;

In the both of above examples the values in the variable remains same but we used different ways to store the data.

if you do not specify a key for given value then the maximum of integer indices is taken till there, and the new key will be that maximum value+1.

if you you specify a key value that already assigned that value will be overwritten.

Multi dimension array:

An array containing one or more arrays in a multi dimension at array, each element in the main array can also be an array and each element in the sub array and so on..

if you want to remove a value from the array you need to use the function unset();
syntax: unset($age[‘x’]);

You Might Also Like