Arrays in PHP – Tutorial

What is an array?

In computer science an array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type, in PHP however each element can be a different data type. Each element of an array has a unique identifying index number. Changes made to one element of an array do not affect the other elements.

The syntax of an array is almost identical to the syntax of other variables in PHP. It follows the same rules regarding variable names, and can be referenced in the same way as any other variable. There are, however, differences in how the data within an array is accessed and how an array is created.

Arrays in PHP

There are three different kind of arrays:

  • Numeric array – An array with a numeric key
  • Associative array – An array where each key is associated with a value
  • Multidimensional array – An array containing one or more arrays

PHP internally stores all arrays as associative arrays, so the only difference between associative and indexed arrays is what the keys happen to be. Some array features are provided mainly for use with indexed arrays, because they assume that you have or want keys that are consecutive integers beginning at 0. In both cases, the keys are unique, you can’t have two elements with the same key, regardless of whether the key is a string or an integer.

Creating Numeric arrays

We first start with creating an Indexed or Numerical array. In this example, we will create an indexed array consisting of some colors (our data elements). The position of first element will be zero by default.

1
2
3
<?php
$colors = array("Red","Blue","Green","Yellow");
?>

The array we have just created looks like this. Notice how the index starts at 0 by deafault.

Array
(
    [0] => Red
    [1] => Blue
    [2] => Green
    [3] => Yellow
) 

You can also create this array in 2 other ways:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
 
$colors[0] = "Red";
$colors[1] = "Blue";
$colors[2] = "Green";
$colors[3] = "Yellow";
 
 
// or
 
$colors[] = "Red";
$colors[] = "Blue";
$colors[] = "Green";
$colors[] = "Yellow";
 
 
?>

Creating Associative arrays

You have the possibility to use more meaningful keys. Associative array means that you can assign an arbitray key to every value. Associative arrays are sometimes referred to as dictionaries. Our colors array can be defined as associative array like this:

1
2
3
4
5
6
7
8
9
<?php
 
$colors = array(
				"apple" => "red",
				"sky" => "blue",
				"grass" => "green", 
				"banana" => "Yellow"
				);
?>

The array we have created now looks like this

Array
(
    [apple] => red
    [sky] => blue
    [grass] => green
    [banana] => Yellow
)

Again, there is a different way to create this array:

1
2
3
4
5
6
<?php
$colors["apple"] = "red";
$colors["sky"] = "blue";
$colors["grass"] = "green"; 
$colors["banana"]= "Yellow";
?>

Creating Multidimensional arrays

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array.

In this example we create a multidimensional array, with automatically assigned ID keys:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
$families = array(
                  "Simpson" => array(
                                     "Homer", 
                                     "Marge", 
                                     "Bart",
                                     "Lisa",
                                     "Maggie"
                                    ),			   
                  "Szyslak" => array("Moe"),
                  "Flanders" => array(
                                   "Ned",
                                   "Maude", 
                                   "Todd",
                                   "Rod"
								   )
	);
?>

The array above would look like this:

  Array
(
    [Simpson] => Array
        (
            [0] => Homer
            [1] => Marge
            [2] => Bart
            [3] => Lisa
            [4] => Maggie
        )

    [Szyslak] => Array
        (
            [0] => Moe
        )

    [Flanders] => Array
        (
            [0] => Ned
            [1] => Maude
            [2] => Todd
            [3] => Rod
        )

)
  

Again, there are different ways to create this array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
 
$families["Simpson"][] = "Homer";
$families["Simpson"][] = "Marge";
$families["Simpson"][] = "Bart";
$families["Simpson"][] = "Lisa";
$families["Simpson"][] = "Maggie";
 
$families["Szyslak"][] = "Moe";
 
$families["Flanders"][] = "Ned";
$families["Flanders"][] = "Maude";
$families["Flanders"][] = "Todd";
$families["Flanders"][] = "Rod";
 
// or
 
$families["Simpson"][0] = "Homer";
$families["Simpson"][1] = "Marge";
$families["Simpson"][2] = "Bart";
$families["Simpson"][3] = "Lisa";
$families["Simpson"][4] = "Maggie";
 
$families["Szyslak"][0] = "Moe";
 
$families["Flanders"][0] = "Ned";
$families["Flanders"][1] = "Maude";
$families["Flanders"][2] = "Todd";
$families["Flanders"][3] = "Rod";
 
?>

Accessing the array elements

You access the contents using the array name and a key, so you can access the information stored in the families array as $families["Flanders"][3], $families["Simpson"][2], and $families["Szyslak"][0].

Using loops

To access the data stored in the array, one can manualy echo each piece of the array. This is not verry effective, when the array grow, so does the amount of effort one has to put into outputting the data. This is why you use a looping construct to do this work for you.

The for loop

The for loop has three statements.

  • In the first statement, we initialize a counter variable.
  • In the second statement, we set a condition (a max/min number value) until the counter is reached.
  • In the third statement, we set a value by how much we want the counter variable to incremented by.

In this example the for loop, itterates through the array $colors and prints each item on the screen.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
 
$colors = array("Red","Blue","Green","Yellow");
 
 
	for($i=0; $i<=3; $i++)
	{
		echo $colors[$i]."<br>";
	}
 
 
?>

Output:

Red
Blue
Green
Yellow
Using the foreach loop

Foreach loop is most often used to print elements in a array.

1
2
3
4
5
6
7
8
9
10
11
12
<?php
 
$colors = array("Red","Blue","Green","Yellow");
 
 
	foreach($colors as $color)
	{
		echo $color."<br>";
	}
 
 
?>

Output:

Red
Blue
Green
Yellow
Using the foreach loop with associative arrays

When using associative arrays the indices in an array are not numbers, you cannot use a simple counter in a for loop to work with the array. However, you can use the foreach loop.

The foreach loop has a slightly different structure when using associative arrays. You can use it exactly as in the previous example, or you can incorporate the keys as well:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php 
 
$colors = array(
				"apple" => "red",
				"sky" => "blue",
				"grass" => "green", 
				"banana" => "Yellow"
				);
 
 
	foreach ($colors as $fruit => $color) {
 
		echo $fruit. ' is '.$color.'<br>';
 
	}
 
?>

Output:

apple is red
sky is blue
grass is green
banana is Yellow
5 Comments
  1. Baldev says:

    I liked tutorial on arrays on your site. It is very simple to understand on ur site. Thanks

    Reply
  2. jim s says:

    the tutorial on arrays is very good, but there is very little on the net talking about taking a multi-dimensional array and putting it in a file for future processing. also there is little/nothing on reading a multi-dimensional array out of a file and working with the nodes. if you know of something that fits either situation, i would appreciate your mentioning it.

    Reply
  3. Ansari Shareef says:

    I like all the tutorial offered by this site. They are explained breifly that even a biggener
    can learn them easily. Thanks for this service

    Reply
  4. good job bro!

    Reply
Trackbacks / Pings
Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


− 1 = two