Chapter 7 Exercises

Exercise 5: Creating Multidimensional Arrays

Multidimensional arrays are both simple and complex at the same time. The structure and concept can be somewhat difficult to grasp, but it is surprisingly easy to create and access multidimensional arrays in PHP.

With a multidimensional array you can create an array that contains more information than a standard array. This is accomplished by using other arrays for values rather than strings and numbers. For example:

The multidimensional array in PHP.

This array, $groceries, now consists of one string (peanuts), one floating-point number (30.00), and two arrays (fruits and meats).

Pointing to an element in an array within an array is tricky. The key (pardon the pun) is to continue adding indices in square brackets as necessary. So in this example, bananas is at $groceries[‘fruits’][1].

First, you point to the element (in this case, an array) in the $groceries array, by using [‘fruits’]. Then, you point to the element in that array based on its position. Because it is the second item, you use the index [1].


In this exercise you will write a PHP script for a different scenario. Your task now is to create a multidimensional array containing the chapters for three books.

Note: A number of Helpful Tips are located at the end of this web page for reference as you complete this exercise.

To use multidimensional arrays:

  1. You will create a PHP script (Script 7-4):
    Script 7-4: The multidimensional $books array stores a lot of information in one big variable.
    The PHP scripts that store lots of information in one big variable using a multidimensional $book array as displayed in the editor view.
  2. To begin, create a new HTML document (Script 7-4) with the title My Books and Chapters:
    A new HTML document with the title My Books and Chapters as displayed in the editor view.
  3. Create the initial PHP tags, and address error handling, if necessary:
    The PHP code snippet that creates the initial PHP tags, and addresses error handling as displayed in the editor view.
  4. Create the first array:
    The PHP array $janeeyre(which is short for Jane Eyre) that uses numbers for the keys and strings for the values as displayed on the editor view.
    To build up the multidimensional array, you will create three standard arrays and then use them as the values for the larger array. This array (called $janeeyre, which is short for Jane Eyre) uses numbers for the keys and strings for the values. The numbers begin with 1 and correspond to the chapter numbers. The values are the chapter titles.
  5. Create the next two arrays:
    The second, third array examples in the PHP as displayed in the editor view.
    For each array, you only need to add the first four chapters from each book for simplicity’s sake.
  6. Create the main multidimensional array:
    The PHP code snippet that creates the main multidimensional array as displayed in the editor view.
    The $books array is the master array for this script. It uses strings for keys (which are shortened versions of the book titles) and arrays for values. Here you are using the array() function to create the array.
  7. Print out the name of the third chapter of the Jane Eyre book:
    The PHP print code that prints out the name of the third chapter of the Jane Eyre Book as displayed in the editor view.
    Following the rules stated earlier, all you need to do to access any individual chapter name is to begin with $books, follow that with the first index ([‘Jane Eyre’]), and follow that with the next index ([3]). Because you are placing this in a print() statement, you will enclose the whole construct in curly braces to avoid parse errors.
  8. Print out two more examples:
    The PHP code snippet that prints out two more examples as displayed in the editor view.
  9. Run the $books array through a foreach loop to see the results:
    The PHP code snippet that runs the $books array through a foreach loop to see the results as displayed in the editor view.
    The $key variable stores each abbreviated book title, and the $value variable ends up containing each chapter array.
  10. Close the PHP section and complete the HTML page:
    The closing tags that close the PHP section and complete the HTML pages as displayed in the editor view.
  11. Save the script as books.php to your XAMPP folder (c:\XAMPP\htdocs\202\chapter7).
  12. Using Cyberduck, upload the file to the production server, and test in your browser (Figure 7-5), making sure you are looking at the production server version of the file.
    Figure 7-5: The first three lines are generated by print() statements. The last three show the results of the foreach loop. As each variable for each book contains an array, notice the word Array appears. See the Tips section lower down on this page for a solution for fixing this issue.
    The HTML view that shows the first three lines are generated by print() statements and foreach loop as displayed in the browser view.
Important: If something doesn’t look right in your document, and you need to make changes to the script, follow the editing procedure using Synapse outlined in Chapter 1.

 

Quick tips icon.

  • To access every element of every array, you can nest two foreach loops like this (Figure 7-6):
    The PHP code snippet that nests two foreach loops to access every element of every array.
    Figure 7-6: One foreach loop within another can access every element of a multidimensional array.
    The HTML view that shows one foreach loop within another can access every element of a multidimensional array as displayed in the browser view.
  • Using the print_r() or dump() function (preferably enclosed in HTML <pre> tags for better formatting), you can view an entire multidimensional array (Figure 7-7).
    Figure 7-7: The var_dump() function shows the structure and contents of the $books array.
    The var_dump() function example that shows the structure and contents of the $book array as displayed in the browser view.
  • You can create a multidimensional array in one statement by using a series of nested array() calls (instead of using several steps as in this example). However, doing so is not recommended. This is because it is all too easy to make syntactical errors as a statement becomes more and more nested.
  • Although all the sub-arrays in this example have the same structure (numbers for indexes and four elements), such consistency is quite unusual with multidimensional arrays. Real-world examples will vary greatly.

Return to Chapter 7, Assignments Page