Working with Arrays - PHP Language Structure - Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Part II. PHP Language Structure

Chapter 8. Working with Arrays


In this chapter, you learn the following:

How to create associative and multidimensional arrays

How to use the myriad array-related functions built in to PHP


Arrays are used to store and organize data. PHP includes many functions that enable you to create, modify, and manipulate arrays, which you use often throughout the procedural programming method described in this book.

What Are Arrays?

You’ve already learned about and used scalar variables in the earlier chapters in this book, and therefore you know that these variables are used to store values. But scalar variables can store only one value at a time—the $color variable can hold only a value of red or blue, and so forth, but it cannot be used to hold a list of colors in the rainbow. But arrays are special types of variables that enable you to store as many values as you want, including all seven of those rainbow colors.


Caution

Although you can store as many values as you want in an array, some array functions have an upper limit of 100,000 values. If you are storing large amounts of data in your arrays, be sure to read the PHP Manual entry for array functions you want to use and find out whether the function has an upper limit for working with data.


Arrays are indexed, which means that each entry is made up of a key and a value. The key is the index position, beginning with 0 and increasing incrementally by 1 with each new element in the array. The value is whatever value you associate with that position—a string, an integer, or whatever you want. Think of an array as a filing cabinet and each key/value pair as a file folder. The key is the label written on the top of the folder, and the value is what is inside. You’ll see this type of structure in action as you create arrays in the next section.

Creating Arrays

You can create an array using either the array() function or the array operator []. The array() function is usually used when you want to create a new array and populate it with more than one element, all in one fell swoop. The array operator is often used when you want to create a new array with just one element at the outset, or when you want to add to an existing array element.

The following code snippet shows how to create an array called $rainbow using the array() function, containing all its various colors:

$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo",
"violet");

The following snippet shows the same array being created incrementally using the array operator:

$rainbow[] = "red";
$rainbow[] = "orange";
$rainbow[] = "yellow";
$rainbow[] = "green";
$rainbow[] = "blue";
$rainbow[] = "indigo";
$rainbow[] = "violet";

Both snippets create a seven-element array called $rainbow, with values starting at index position 0 and ending at index position 6. If you want to be literal about it, you can specify the index positions, such as in this code:

$rainbow[0] = "red";
$rainbow[1] = "orange";
$rainbow[2] = "yellow";
$rainbow[3] = "green";
$rainbow[4] = "blue";
$rainbow[5] = "indigo";
$rainbow[6] = "violet";

However, PHP handles this numbering for you when positions are not specified, and that eliminates the possibility that you might misnumber your elements when order is important, as in this example:

$rainbow[0] = "red";
$rainbow[1] = "orange";
$rainbow[2] = "yellow";
$rainbow[5] = "green";
$rainbow[6] = "blue";
$rainbow[7] = "indigo";
$rainbow[8] = "violet";

Regardless of whether you initially create your array using the array() function or the array operator, you can still add to it using the array operator. In the first line of the following snippet, six elements are added to the array, and one more element is added to the end of the array in the second line:

$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo");
$rainbow[] = "violet";

The examples used in this section are of numerically indexed arrays, arguably the most common type you’ll see. In the next two sections, you learn about two other types of arrays: associative and multidimensional.

Creating Associative Arrays

Whereas numerically indexed arrays use an index position as the key—0, 1, 2, and so forth—associative arrays use actual named keys. The following example demonstrates this by creating an array called $character with four elements:

$character = array(
"name" => "Bob",
"occupation" => "superhero",
"age" => 30,
"special power" => "x-ray vision"
);

The four keys in the $character array are name, occupation, age, and special power. The associated values are Bob, superhero, 30, and x-ray vision, respectively. You can reference specific elements of an associative array using the specific key, such as in this example:

echo $character['occupation'];

The output of this snippet is this:

superhero

As with numerically indexed arrays, you can use the array operator to add to an associative array:

$character['supername'] = "Mega X-Ray Guy";

This example adds a key called supername with a value of Mega X-Ray Guy.

The only difference between an associative array and a numerically indexed array is the key name. In a numerically indexed array, the key name is a number. In an associative array, the key name is a meaningful word.

Creating Multidimensional Arrays

The first two types of arrays hold strings and integers, whereas this third type holds other arrays. If each set of key/value pairs constitutes a dimension, a multidimensional array holds more than one series of these key/value pairs. For example, Listing 8.1 defines a multidimensional array called $characters, each element of which contains an associative array. This might sound confusing, but it’s really only an array that contains another array.

Listing 8.1 Defining a Multidimensional Array


1: <?php
2: $characters = array(
3: array(
4: "name" => "Bob",
5: "occupation" => "superhero",
6: "age" => 30,
7: "special power" => "x-ray vision"
8: ),
9: array(
10: "name" => "Sally",
11: "occupation" => "superhero",
12: "age" => 24,
13: "special power" => "superhuman strength"
14: ),
15: array(
16: "name" => "Jane",
17: "occupation" => "arch villain",
18: "age" => 45,
19: "special power" => "nanotechnology"
20: )
21: );
22: ?>


In line 2, the $characters array is initialized using the array() function. Lines 3–8 represent the first element, lines 9–14 represent the second element, and lines 15–20 represent the third element. These elements can be referenced as $characters[0], $characters[1], and $characters[2].

Each element consists of an associative array, itself containing four elements: name, occupation, age, and special_power.

However, if you attempt to print the master elements like so

echo $characters[1];

the output will be

Array

because the master element indeed holds an array as its content. To really get to the content you want (that is, the specific information found within the inner array element), you need to access the master element index position plus the associative name of the value you want to view.

Take a look at this example:

echo $characters[1]['occupation'];

It prints this:

superhero

If you add the following lines to the end of the code in Listing 8.1, it prints the information stored in each element, with an added line displayed in the browser for good measure:

foreach ($characters as $c) {
while (list($k, $v) = each ($c)) {
echo "$k ... $v <br/>";
}
echo "<hr/>";
}

The foreach loop is concerned with the master array element, $characters. It loops through this array and assigns the temporary name $c to the element contained within each position. Next, the code begins a while loop. This loop uses two functions to extract the contents of the inner array. First, the list() function names placeholder variables, $k and $v, which will be populated with the keys and values gathered from the each() function. The each() function looks at each element of the $c array and extracts the information accordingly.

The echo statement simply prints each key and value ($k and $v) extracted from the $c array using the each() function and adds a line break for display purposes. Figure 8.1 shows the result of this file, called mdarray.php.

image

Figure 8.1 Looping through a multidimensional array.

Some Array-Related Constructs and Functions

More than 70 array-related functions are built in to PHP, which you can read about in detail at http://www.php.net/array. Some of the more common (and useful) functions are described briefly in this section:

count() and sizeof()—Each of these functions counts the number of elements in an array; they are aliases of each other. Given the following array

$colors = array("blue", "black", "red", "green");

both count($colors); and sizeof($colors); return a value of 4.

each() and list()—These functions (well, list() is a language construct that looks like a function) usually appear together, in the context of stepping through an array and returning its keys and values. You saw an example of this previously, where we stepped through the $c array and printed its contents.

foreach()—This control structure (that looks like a function) is used to step through an array, assigning the value of an element to a given variable, as you saw in the previous section.

reset()—This function rewinds the pointer to the beginning of an array, as in this example:

reset($character);

This function proves useful when you are performing multiple manipulations on an array, such as sorting, extracting values, and so forth.

array_push()—This function adds one or more elements to the end of an existing array, as in this example:

array_push($existingArray, "element 1", "element 2", "element 3");

array_pop()—This function removes (and returns) the last element of an existing array, as in this example:

$last_element = array_pop($existingArray);

array_unshift()—This function adds one or more elements to the beginning of an existing array, as in this example:

array_unshift($existingArray, "element 1", "element 2", "element 3");

array_shift()—This function removes (and returns) the first element of an existing array, as in this example, where the value of the element in the first position of $existingArray is assigned to the variable $first_element:

$first_element = array_shift($existingArray);

array_merge()—This function combines two or more existing arrays, as in this example:

$newArray = array_merge($array1, $array2);

array_keys()—This function returns an array containing all the key names within a given array, as in this example:

$keysArray = array_keys($existingArray);

array_values()—This function returns an array containing all the values within a given array, as in this example:

$valuesArray = array_values($existingArray);

shuffle()—This function randomizes the elements of a given array. The syntax of this function is simply as follows:

shuffle($existingArray);

This brief rundown of array-related functions only scratches the surface of using arrays. However, arrays and array-related functions are used in the code examples throughout this book, so you will get your fill soon enough. If you don’t, there’s always the array section of the PHP Manual athttp://www.php.net/array that discusses all array-related functions in great detail, including more than 10 different methods just for sorting your arrays.

Summary

This chapter introduced you to the concepts of arrays, including how they are created and referenced. The three array types are the numerically indexed array, associative array, and multidimensional array. In addition, you saw examples of some of the numerous array-related functions already built in to PHP. You can use these functions to manipulate and modify existing arrays, sometimes even creating entirely new ones.

Q&A

Q. How many dimensions can multidimensional arrays have?

A. You can create as many dimensions in your multidimensional array as you can manage, but remember the more dimensions you have, the more you have to manage. If you have data with more than a few dimensions, it might be wise to ask yourself whether that data should be stored differently, such as in a database and accessed that way.

Q. If all I’m doing is creating a contact form, why would I care about arrays?

A. Arrays are useful in even the most basic client-server interactions, such as a contact form in a website. You will learn more about forms in Chapter 11, “Working with Forms,” but here’s something to keep in mind before you work with the information in that chapter: If your form contains any series of checkboxes or lists from which a user can select more than one option, that data will be sent to your form as an array. You’ll need to get that data out of the array if you want to work with it, and this chapter shows a few basic examples of doing just that.

Workshop

The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.

Quiz

1. What construct can you use to define an array?

2. What function would you use to join two arrays?

Answers

1. array()

2. array_merge()

Activities

1. Review the process of defining a multidimensional array and referencing its items.

2. Create a multidimensional array of movies organized by genre. This should take the form of an associative array with genres as keys, such as Science Fiction, Action, Adventure, and so forth. Each of the array’s elements should be an array containing movie names, such as Alien,Terminator 3, Star Wars, and so on. After creating your arrays, loop through them, printing the name of each genre and its associated movies.