Skip to main content

PHP Array Tutorial – A Complete Coverage of PHP Array

The array is one of the most useful data types in PHP programming. PHP has the various built-in function to operate on the array which makes array very easy to use. In this tutorial, we will explore every aspect of PHP array.

What is Array

The array is a special kind of data type which stores data in tabular or tree form. Or in another word we can say that it is compound data type which stores multiple information in a single variable. In the array, every value or information has an address which known as a key. In the array, we access the value by using key or address. On the basis of data placement in the array we can category array in two type:

  1. Single Dimension Array
  2. Multidimensional Array

1) Single Dimension Array: In single dimension array data placement is horizontal. In another word single dimension, an array is an array which stores a single information on the one address. Below is the example of single dimension array.

PHP ArrayAbove image is a visual explanation of array. Above image describes a single array which contains 5 integer value. Every value has its own address eg. value 1 has address 0, value 2 has address 1.

2) Multidimensional Array: Multidimensional array is true tabular information representation. In multidimensional array every address itself store array. Below is the visual representation of the multidimensional array.

PHP Multidimensional arrayHere the Main array is represented by its value with a dot(.) Now every dot(.) itself contains an array. So by using this technique we can create table or tree using an array.

In PHP array key can be numeric or string. 

Use of Array in PHP

Usually, we use an array in PHP to store multiple information related to a single entity. For example database server information in which we need to store database host, database username, database name, database password. Since array stores values in tabular and tree from, we can use an array to store information any type of tabular or tree representation of data. For example, we can store complete database table data with the information. Following are the general use of array in PHP

  1. For vector list
  2. For Creating Hash Table
  3. For Creating Tree
  4. For Implementation of Stack or Queue

How to Create or Specify PHP Array

The most popular way to create an array in PHP is by using array() function. But still, there is some other way to create an array in PHP. Here we will explore all possible way to create an array in PHP.

1) Array creation by using array() language construct: The most common way to create an array is by using array() language construct. We need to pass a key value in the array() language construct. Every key value pair will of key=>value. Also, we need to add a comma after every key value pair element.  For example
$a = array('key1'=>'value1' , 'key2' => 'value2' , 'key3'=>'value2' ...);
In the array function, we do not have any limitation on a number of key value pair. We can any number of key, value pair in the array() function. Key of the array can be either integer or string. We can also create an array without using the key. Example:
$a = array('apple' , 'banana' ,'oragne');
If we will create an array without using key then PHP will add integer(starting from 0) key automatically in the array. So Internally above array will be like below:
$a = array(0=>'apple' ,1 => 'banana' ,2=>'oragne');

array() is not a regular function in PHP. array() is a language construct in PHP

Array key can be numeric or string. Array with string key or index is associative array.Eg.
$a = array(
1=>'Ankur',
2=>'Ankur 2',
'name' =>'Ank',
3=>'other name'
);

In above example, the name is also a key which is a string. Now above array is associative PHP array.

We can also create a multidimensional PHP array using array(). Below is example of a multidimensional array:

$a = array(
'vegetable'=> array('tomato' , 'carrot' , 'zucchini' , 'cabbage'),
'counter' => array(1,2,3,4,5,6,7),
'mix'=>array(0=>'Ankur' , 1=>'Ajay', 'No Name' , 'first_name' => 'Anks')
);

Above is a multidimensional array. Above array is having lots of variation.

2) Creating PHP array on run time: As we know that PHP has automatic type conversion. We can create an array in PHP on run time using the square bracket. Ex:
$a[0] = "Tomato";
$a[1] = "Potato";
$a[2] = "Carrot";
$a['fruit'] = "Banana";

Here we are specifying array key in []. In top 3 line keys are integer(1,2,3). But on 4th line key is fruit. So again in this method, you can easily construct any type of array key /element variation.

In array, we can also specify automatic key addition. Below is the example
$a[0] = "Tomato";
$a[1] = "Potato";
$a[2] = "Carrot";
$a[] = "Cabbage";

The last element is assigned value only by using []. In [] we have not specified any key. So it will automatically take next available integer. So here array index for the cabbage will be 3. We can also use this practice with an associative array.
$a[0] = "Tomato";
$a[1] = "Potato";
$a[2] = "Carrot";
$a['name'] = "Ankur";
$a[] = "Cabbage";

Again in the above array next available integer index is 3. So cabbage will have index value 3. But in below example:
$a[21] = "Tomato";
$a[43] = "Potato";
$a[51] = "Carrot";
$a['name'] = "Ankur";
$a[] = "Cabbage";

Next available index is 52. So value cabbage will have index 52.

We can also create a multidimensional PHP array using following technique.
$a[0] = "Tomato";
$a[1] = "Potato";
$a[2][1] = "Carrot";
$a['name'] = "Ankur";
$a[] = "Cabbage";

Now in above example $a[2][1] is multidimensional array representation. It denotes that $[2]  itself is an array. And $a[2] array’s index 1 is having variable value ‘Carrot’.
We can also define a multidimensional array like below(internal representation of the below PHP array is same as above example):
$a[0] = "Tomato";
$a[1] = "Potato";
$a[2] = array(1=>"Carrot");
$a['name'] = "Ankur";
$a[] = "Cabbage";

3) Creating array with square bracket as of PHP 5.4:  From PHP 5.4 onward you can create PHP array quickly using below technique:
$a = [
'key1'=>'Value1',
'key2' =>'value2'
];

Accessing Array Element Value 

We can access an element of the array by key. In PHP array we need to pass element key in the square bracket to access value of the array element. Eg:
$a= array(0=>'Banana' , 1=>'Apple' , 2=>'Grape');
echo $a[0];//Print banana.
echo $[1];//Print Apple
echo $a[2]// Print Grape

If the key is string we need to pass string the array:
$a = array(0=>'Banana' , 1=>'Apple' , 'name'=>'Carrot');
echo $a[1];//Print Apple
echo $a['name'];//Print Carrot

If the array is multidimensional then for every dimension we need to specify square bracket. Eg:
$a= array(2=>'Carrot' , 'fruit' => 'Banana' , 'counter'=>array(1,2,3), 'random'=>array(2=>array('Ank')) , 5=>array(9, 7));
echo $a[2];// Print carrot;
echo $a['fruit'];//Print Banana
echo $a['counter'][0];//Print 1
echo $a['random'][2][0]; Print Ank
echo $a[5][0];//Print 9

To print array recursively we can use function print_r() or var_dump() function. Print_r method will print array recursively in human readable format. Var_dum also prints array recursively but it gives you debugging information about the array also. For Example:
$a= array(2=>'Carrot' , 'fruit' => 'Banana' , 'counter'=>array(1,2,3), 'random'=>array(2=>array('Ank')) , 5=>array(9, 7));
print_r($a);

It will print the output following format.

Array
(
    [2] => Carrot
    [fruit] => Banana
    [counter] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [random] => Array
        (
            [2] => Array
                (
                    [0] => Ank
                )

        )

    [5] => Array
        (
            [0] => 9
            [1] => 7
        )

)


$a= array(2=>'Carrot' , 'fruit' => 'Banana' , 'counter'=>array(1,2,3), 'random'=>array(2=>array('Ank')) , 5=>array(9, 7));
bar_dump($a);

It will print the output following format.

array(5) {
  [2]=>
  string(6) "Carrot"
  ["fruit"]=>
  string(6) "Banana"
  ["counter"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  ["random"]=>
  array(1) {
    [2]=>
    array(1) {
      [0]=>
      string(3) "Ank"
    }
  }
  [5]=>
  array(2) {
    [0]=>
    int(9)
    [1]=>
    int(7)
  }
}

Copying PHP array

We can copy PHP array by using assignment operator =.When we will copy the PHP array from one variable to other all keys and corresponding values will be copied. For example:
$a= array(2=>'Carrot' , 'fruit' => 'Banana' , 'counter'=>array(1,2,3), 'random'=>array(2=>array('Ank')) , 5=>array(9, 7));
$b = $a; //Now all values and keys of the $a will be copied to $b.

We can also copy the array variable by reference. Below is the example:
$a= array(2=>'Carrot' , 'fruit' => 'Banana' , 'counter'=>array(1,2,3), 'random'=>array(2=>array('Ank')) , 5=>array(9, 7));
$b =&$a //Now all values and keys of the $a will be copied to $b.
$a['reference'] = 'php array';
print_r($b); //It also contains key 'reference' and with value 'php array'

Array Operators

We can use the following operator in the PHP array:

  1. + For Union
  2. ==  For the Equality Comparison
  3. === For the  Identity Comparison
  4. != For Inequality comparison
  5. !== For Non-identity compression

1) Union Operator +: We can use the union operator with the array to get the union of the 2 array. For example:

$a = array(0=>'Apple' , 1=>'Banana');
$b = array(2=>'Grape' , 3=>'Mango');
$c = $a + $b;//Use of +(union operator) operator 
print_r($c);

//output will be:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Grape
    [3] => Mango
)

But for the following case:

$a = array('Apple' , 'Banana');
$b = array('Grape' , 'Mango');
$c = $a + $b;
print_r($c);

//Output will be

Array
(
    [0] => Apple
    [1] => Banana
)

Because in $a Apple has index 0 and Banana has index 1. Similarly, in $b Grape has index 0 and Mango has 1. Now when we will create union of $a with $b then $a($a + $b) index will be superseded. When you will create union of $b with $a($b + $a) the output will be just opposite. Means the $b indexes will be superseded.

2) Equality and Inequality operators in PHP Array:
We can compare the 2 array using == and !=. For example

$a = array('Apple' , 'Banana');
$b = array('Apple' , 'Banana');
if($a == $b)
{
echo 1;
}

Or
$a = array('Apple' , 'Banana' , 'Grape');
$b = array('Apple' , 'Banana');
if($a != $b)
{
echo 1;
}

To ready further about PHP Array you can refer to below URL:

http://in1.php.net/manual/en/language.types.array.php

 

 

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

One thought to “PHP Array Tutorial – A Complete Coverage of PHP Array”

Leave a comment/Ask Question

shares