Arrays and how they hold multiple chunks of data

This page is marked as In Progress so expect small errors or unfinished bits

You can think of a variable as a box which can hold one item:

variable shown as a box containing one item

If you want to hold more than one item you have more than one variable (each with it's own name):

three separate variables

An array is the alternative - a collection of items held in one container (with just one name to remember):

array shown as a box containing multiple items in compartments

You could hold the same items of data in a number of separate variables but it is normally easier to use an array.

The simplest way to access arrays

Each of the elements in an array contains a piece of data. To get to the data you need to point to which element you want. The easiest way is to use numbers. The only slight confusion is that, by default, the numbers start at zero:

array shown as a box containing one item with items numbered

The array has one name but inside it are values which you can point to using a number. In the code the number is normally put inside square brackets. In PHP this looks like:

$numbers[0];          
        

This allows you to access the first "box" of data within the array (here that is the number 4).

Multi-dimensional arrays

An array can normally hold other arrays:

a multidimensional array

The main array is still there but within each element of that array is another. These sub-arrays hold the actual data. Doing this you can save data about an item. The three elements of the sub-arrays could hold user names, dates and scores to record use of your on-line game:

Freda1/1/112345
Fred10/10/113456
Joanne5/5/114567

The rows of the table are the elements in the main array. Each sub-array has data just about that one row or "record" - one person's score and the date they played.

The data in the "table" can be accessed like this in JavaScript:

user=scores[1][0];
date=scores[1][1];
score=scores[1][2];
        

This will extract the user name, date and score for the second record (Fred, 10/10/11 and 4567).

submit to reddit Delicious Tweet