Storing & retrieving data with Arrays

By the end of this post you will be able to:

  • 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

Let’s unpack these:

Numeric or Indexed Arrays

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

//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";

echo "The plays $plays[0], $plays[1] are written by William Shakespeare. 
"; echo "The theatres $theatres[0], $theatres[1], $theatres[2] are situated in London.
";

Associative arrays

Characteristics of an associative array:

  • Instead of a numerical index you can apply a name to be an index
  • You then apply values to that index
//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.
"; //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'];

Note: With indexes in associative arrays you can use spaces

Multi-dimensional arrays

Characteristics of Multi-dimensional arrays:

  • You can create an array of arrays
  • Each item in the array is another list of items

Multi-dimensional Array – Static

Here we are creating a two dimensional array and using it to group items by category.

$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"; 

We are referencing the parent array using an associative key and pulling a specific record from the child array below it. So the output here will be:

Macbeth

You can have as many dimensions to an array as you like but be careful any more than three or four dimensions and things can get a bit out of control!

What is a good use case for multi-dimensional arrays?

Multi-dimensional arrays are great for capturing large amounts of structured data. For example relational datasets. Given the multidimensional structure they are arguably great for reducing the load on the server and the amount of database calls required – you can make one call and capture relational data several layers deep. You can then either process that data in PHP or pass it in for instance a JSON format for processing using JavaScript.

Let’s create a simple shopping cart example

Using a grocery shop lets create a multidimensional array that stores products, quantities and prices. We can then use a loop to spit out the results to the viewport.

//Accessing data in multi-dimensional arrays
//Create array

$grocery_shop = array( array("Apples", 0.30 , 9),
               array("Kiwi", 1.15 , 12),
               array("Oranges", 0.40 , 6) 
             ); 

//Shop array now contains three arrays	

//With one dimensioanl arrays you need the array name and index 
//In two dimensional arrays you need row and column
//Bit like a table > Table name > table row > Table column

//You can access data manually - like so

echo "<h1>Manual access to each element </h1>";

echo $grocery_shop[0][0]." costs ".$grocery_shop[0][1]." and you get ".$grocery_shop[0][2]."
"; echo $grocery_shop[1][0]." costs ".$grocery_shop[1][1]." and you get ".$grocery_shop[1][2]."
"; echo $grocery_shop[2][0]." costs ".$grocery_shop[2][1]." and you get ".$grocery_shop[2][2]."
"; //Remember arrays start with zero echo "<h1>Using loops to display array elements</h1>"; echo "
    "; for ($row = 0; $row < 3; $row++) { echo "<li>The row number $row</li>"; echo "
      "; for ($col = 0; $col < 3; $col++) { echo "
    • ".$grocery_shop[$row][$col]."
    • "; } echo "
    "; echo ""; } echo "
";

What have we explored in this post?

We have demonstrated:

  • What arrays are
  • Identified how and when to use arrays
  • Identified the difference between Indexed, Associative and Multi-dimensional arrays
  • Applied practical examples of arrays
  • Demonstrated how to use loops with arrays
No Comments

Post a Comment