Arrays 101

Arrays are one of the most importat tools for any developer. It help to orgenize data from a simple to a complex structures. The most used styled arrays are indexical and associative arrays.

We will start with the most basic array and then see a multi dimentional array.

Simple array

lets write one simple array:

$names = array('John','Simon','Nick');

We created a variable which contain an array of names. In order to view the array we can write:


And the output will look like this:



    [0] => John

    [1] => Simon

    [2] => Nick


We have an array with all the names.The values in the square brackets are the kays. In indexical arrays the keys will be numbers automatically and it always start with zero. But what if we want to orgenize a more human readable array? we can enter our own keys like so:

$names = array('name1' =>'John','name2' =>'Simon','name3' =>'Nick');

And when we output it to the screen we will see:



    [name1] => John

    [name2] => Simon

    [name3] => Nick



As you can see now we have full control over the array.
Multi dimentional array:

A multi dimentional array allow us to create a more complex data structure, it is an array within an array:

$people = array(

			"person1" => array("first name" => "John","last name" => "Taylor", "age" => 45),

			"person2" => array("first name" => "Simon","last name" => "Le-bon", "age" => 50),

			"person3" => array("first name" => "Nick","last name" => "Roads", "age" => 43)


This array contain some persons and for each person we have an inner array that contain his own details. In order to view this kind of array we need to loop it, in this case we use the foreach loop:

foreach ($people as $person)


	foreach($person as $key => $value)


		echo "$key: $value




Notice that since we deal with a multi dimentional array we use a loop within a loop to extract the data, this will be our result:

first name: John

last name: Taylor

age: 45

first name: Simon

last name: Le-bon

age: 50

first name: Nick

last name: Roads

age: 43

With this example we end our tutorial. We only scratched the surface of this subject but it does give a good basic understanding (i hope). I would recommend for anyone who is interested to go to the php functions list for arrays to learn and see how much we can do with arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.