Chapter 7 Exercises

Exercise 3: Adding Items to an Array

Once an array exists in PHP, you can add extra elements to the array with the assignment operator (the equals sign), much like you can assign a value to a string or a number. When adding extra elements to the array, you can choose to either specify the key of the added element or leave this unspecified. In either case, you must refer to the array with the square brackets ([]). To add two items to the $list array, you would write:

The PHP code snippet that adds two items to the $list array.

If you do not specify the key, each element will be appended to the existing array, indexed with the next sequential number. Assuming this is the same array from the previous section, which was indexed at 1, 2, and 3, pears will now be located at 4 and tomatoes at 5.

If you do specify the index, the value will be assigned at that location. Any existing value already indexed at that point will be overwritten, like so:

The PHP code snippet that adds two items to the $list array with the index.

As a result, the value of the element in the fourth position of the array will now be tomatoes, and no element of $list will be equal to oranges (this value will be overwritten by pears). With this in mind, unless you intend to overwrite existing data, you are best not to include a specific key when adding values to your arrays. However, if the array uses strings for indices, you will probably want to specify keys so you do not end up with an odd combination of string and number keys.


In this exercise you will test this process by rewriting coffee_types.php to add more elements to the array. To see the difference this will cause, you will be printing out the number of elements in the array before the new additions and after.

Just as you can find the length of a string— i.e., how many characters it contains—using strlen(), you can determine the number of elements in an array, using count():

The PHP count() function that determines the number of elements in an array.

Note: A number of Helpful Tips are located at the end of this web page for reference as you complete this exercise. There is also an Advanced Topic for additional learning.

Watch this video Example of Arrays in PHP (4:11 min) before attempting the exercises below.

To add elements to an array:

  1. Using Synapse to connect to the production server, open coffee_types.php (Script 7-1) in Brackets:
    Script 7-2: You can directly add elements to an array one at a time by assigning each element a value with the assignment operator. The count() function will help you keep track of how many elements the array contains.
     The PHP script that adds elements to an array one at a time by assigning each element a value with the assignment operator as displayed in the editor view.
  2. After the array is initialized using array(), add the following (Script 7-2):
    The PHP code snippet that counts and prints the current number of elements as displayed in the editor view.
    The count() function determines how many elements are in $coffees. By assigning that value to a variable, you can easily print it out.
  3. Add three more elements to the array:
    The PHP code snippet that adds three more elements to the array as displayed in the editor view.
    This code adds three more coffees— indexed at Medium-Dark, Light-Medium, and Decaf—to the existing array.
  4. Recount how many elements are in the array, and print this value.
    The PHP code snippet that recounts and prints how many elements are in the array as displayed in the editor view.
    This second print() statement is a repetition of the first, letting you know how many elements the array now contains.
  5. Save the script as coffee_types2.php to your XAMPP folder (c:\XAMP\htdocs\202\chapter7).
  6. Using Cyberduck, upload the file to the production server, and test in your browser (Figure 7-3), making sure you are looking at the production server version of the file.
    Figure 7-3: A direct way to ensure that the new elements were successfully added to the array is to count the number of elements before and after you make the additions.
    The HTML page that ensures that the new elements were successfully added to the array 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.

  • Be very careful when you directly add elements to an array. There is a correct way to do this ($array[] = “Add This”; or $array[1] = “Add This”;) and an incorrect way ($array = “Add This”;). If you forget to use the brackets, the added value will replace the entire existing array, leaving you with a simple string or number.
  • The code:
    The PHP code snippet that creates the $array variable if it does not yet exist.
    creates the $array variable if it does not yet exist.
  • While working with these arrays, you are using single quotation marks to enclose both the keys and the values. Nothing needs to be interpolated (like a variable), so double quotation marks are not required. It is perfectly acceptable to use double quotation marks, though, if you wish.
  • You do not (and, in fact, should not) quote your keys if they are numbers, variables, or constants. (You will learn about constants in Chapter 8, Creating Web Applications). For example:
    The PHP code snippet that should not quote your keys if they are numbers, variables, or constants.
  • The sizeof() function is an alias to count(). It also returns the number of elements in an array.

 

Additional/Advanced Reading.

Deleting Arrays and Array Elements.


Return to Chapter 7, Assignments Page