Storing & retrieving data with Arrays

Arrays are like lists. In programming terms arrays are the same as variables that store data but the crucial difference is they store elements of data that is normally related in some way. Think of them a bit like a draw – take a kitchen draw for example that stores kitchen utensils – scissors, wooden spoon, chopping knives etc. An array of related items in one single container.

In this post we will:

  • Describe what arrays are
  • Identify how and when to use arrays
  • Identify the difference between Indexed, Associative and Multi-dimensional arrays
  • Apply practical examples of arrays
  • Demonstrate how to use loops with arrays
  • Apply predefined PHP arrays

What are arrays?

  • Arrays are essentially a list of items
  • They are a variable that is designed to list or hold other variables
  • Arrays can also hold other lists or variables that are arrays

Why would you use arrays?

  • Arrays are designed to hold elements of similar relation to each other
  • They can be used to categorise certain variables within your script
  • They reduce the need to create separate variables, instead place them in one array

What types of array are there?

Arrays come in three distinct flavours:

  • Numeric or Indexed array
  • Associative array
  • Multi-dimensional array

Numeric or indexed array

Characteristics of a numerical or indexed array:

  • Each element in an array is stored with a numerical index
  • An element in that array can be referred by its index
  • All indexes start with zero

Note: All arrays have a numerical index in memory which starts with zero

Let’s a take a look at an example:

//Example 1:  Assigning values directly 
$plays=array("Othello","Hamlet","Antigone","Cats"); 

//Example 2:  Assigning values by index
$theatres[0] = "National Theatre";
$theatres[1] = "The Globe";
$theatres[2] = "Royal Court";
$theatres[4] = "Wales Millenium Centre";
$theatres[5] = "RSC";

//output example 1
echo "The plays $plays[0], $plays[1] are written by William Shakespeare.";

//output example 2
echo "The theatres $theatres[0], $theatres[1],  $theatres[2] are situated in London.";

What’s happening?

Here we are defining two arrays, one for plays and one for theatres. They are defined as keyword array in Example 1 and then assigning values by index in Example 2. If you note when we echo out these examples we use exactly the same indexing methods [ ] brackets.

If nothing else the most important aspect to identify is array position [0]. All arrays start at base zero. So item 3 in Example 2 array is index 2 “Royal Court”.

Associative Arrays

Associative arrays represent data stored as key-value pairs. Imagine the coat pegs you had at primary school. Each peg would have a name associated with it: Peter, Paul, Mary for example! The coat hung on that peg would be the value in programming speak.

Here’s an example of an associative array:

    //In this example we are assigning ages to students
    $student_ages = array("Peter"=>50, "Paul"=>30, "Mary"=>34); 

    echo "Paul is " . $student_ages['Paul'] . " years old.<br/>";

    //This is the same as the above example but shows a different way of assiging values
    $books['Swallows and Amazons'] = "Arthur Ransom";
    $books['Oliver Twist'] = "Charles Dickens";
    $books['Pride and Prejudice'] = "Jane Austen";

    echo "Pride and Prejudice is written by " . $books['Pride and Prejudice'] . "<br>";

   foreach(array_keys($books) as $row)
   {
	if($row == "Pride and Prejudice")
	echo $row . "<br>";
   }

What’s happening?

This outcome demonstrates two examples: an array of student ages and a second array demonstrating books as the key and author as the value. How you display the data is actually the same – they are just defined differently. In the first example we assign values using the “=>” operator which is the array assignment operator.

In the second example we use the [ ] notation to assign values. Both are equally as valid. Notice also that the keys do not have to camelCased or underscored in any way. They just be normally typed.

array_Keys function

This deserves a bit of attention because when working with associative arrays it is sometimes necessary to use the index key as the variable. For example in a car parts database a part number might be the index of a part.

Code snippet

   foreach(array_keys($books) as $row)
   {
	if($row == "Pride and Prejudice")
	echo $row . "<br>";
   }

What’s happening?

array_keys takes the key as value and passes it to $row.

Multi-Dimensional Arrays

The best way to consider Multi-dimensional arrays is to extend our kitchen draw metaphor – imagine a kitchen draw that hold cutlery. Within that draw is a cutlery tray that holds knives, forks, spoons and tea spoons. Each set of cutlery, neatly in its own container could, in application terms be described as a separate sub array contained by the draw – parent array.

Let’s see a multi-dimensional array in action:

  $shakespearePlays = array
  (
   "Comedies"=>array
  (
   "Twelfth Night",
   "Two Gentlemen of Verona",
   "Comedy of Errors"
  ),
   "Histories"=>array
  (
   "Henry V"
  ),
   "Tragedies"=>array
  (
   "Hamlet",
   "Macbeth",
   "Romeo and Juliet"
  )
  ); 
 
  echo "Shakespeare's " . $shakespearePlays['Tragedies'][1] . " is a tragedy"; 

What’s happening?

We have defined an array $shakespearePlays (that’s our draw!) and within that we have created sub arrays which store plays by category (comedies, histories, tragedy) (that’s our cutlery tray…). We then call specific elements from that dimensional array by calling the parent ($shakespearePlays) and a specific element, [‘Tragedies’][1], and index.

With multi-dimensional arrays you have as many dimensions or categories as you like and sub categories beneath.

What is a good use case for dimensional arrays?

Dimensional arrays are great if you need to process large amounts of data that is in specific categories. This may be pulled back from a database with the data situated in several tables. Using this approach will reduce the amount of calls you need to make to the database (a good thing) but then of course there is a trade off because all that data will need to be processed by PHP.

What have we explored?

In this post we have identified what arrays are and the different types, indexed, associative, dimensional. We have analysed the different use cases for each array type in particular dimensional arrays.

The rule of thumb with arrays is that if you can group data or need to work with data as part of a set or collection than arrays are the way to go. The alternative is separate variables which could lead to inefficient processing of data and a code base that could very quickly get out of control.