Creating an Associative Array

PHP is known for its extremely flexible arrays. You can easily generate a number of interesting and useful array types in addition to the ordinary arrays you've already made. One of the handiest types of arrays is called an "associative array."

While it sounds complicated, an associative array is much like a normal array. While regular arrays rely on numeric indices, an associative array has a string index. Figure 5.5 shows a page created with two associative arrays.

Figure 5.5: This page uses associative arrays to relate countries and states to their capital cities.

Examining the assoc.php Program

Imagine that you want to store a list of capital cities. You could certainly store the cities in an array. However, if your main interest is in the relationship between a state and its capital, it could be difficult to maintain the relationship using arrays. In this particular instance, it would be nice if you could use the name of the state as the array index rather than a number.

Building an Associative Array

Here is the code from assoc.php that generates the array of state capitals:

The associative array is just like a normal array, except the index values are strings. Note that the indices must be inside quotes. Once you have created an associative array, it is used much like a normal array, as well.

IN THE REAL WORLD

If all this "associative array" talk is making you dizzy, don't panic. It's actually just a new name for something you're very familiar with. Think about the way HTML attributes work. Each tag has a number of attributes that you can use in any order. For example, a standard button might look like this:

<input type = "button"
value = "Save the world.">

This button has two attributes. Each attribute is made up of a name/value pair. The keywords "type" and "value" are names(or indices, or keys, depending on how you want to think of it) and the terms "button" and "Save the world." are the values associated with those names. CSS uses a different syntax for exactly the same idea. The CSS element

p {background-color:red;
color:yellow;
font-size:14pt}

indicates a series of modifications to the paragraph tag. While the syntax is different, the same pattern applies. The critical part of a CSS definition is a list of name/ value pairs.

There's one more place associative arrays naturally pop up. As information comes into your program from an HTML form, it comes in as an associative array. The name of each element becomes an index, and the value of that form element is translated to the value of the array element. Later in this chapter you'll see how you can take advantage of this.

An associative array is simply a data structure used when the name/value relationship is the easiest way to work with some kind of data.

print "Alaska: ";
print $stateCap["Alaska"];
print "<br><br>";

Once again, note that the index of the array is a quoted string. The associative form is terrific for data like the state capital information. In essence, it lets you "look up" the capital city if you know the state name.

Building an Associative Array with the array() Function

If you know the values you want to have in your array, you can use the array() function to build an associative array. However, building associative arrays requires a slightly different syntax than the garden variety arrays you encountered in the last chapter. I build the $worldCap array using the array() syntax:

When you are building an ordinary array, the array() function requires the data, but doesn't require you to specify the indices. It automatically generates the index of each element by grabbing the next available integer. In an associative array, you are responsible for providing both the data and the index. The general format for this assignment uses a special kind of assignment operator. The => operator indicates an element holds some kind of value. I generally read it as "holds," so you can say "Japan holds Tokyo." In other words, "Japan" => "Tokyo" indicates that PHP should generate an array element with the index "Japan" and store the value "Tokyo" in that element. You can access the value of this array just like any other associative array.

print "Japan: ";
print $worldCap["Japan"];
print "<br><br>";

Using foreach with Associative Arrays

The foreach loop is just as useful with associative arrays as it is with the vanilla kind. However, it uses a slightly different syntax. Take a look at this code from the assoc.php page:

A foreach loop for a regular array uses only one variable because the index can be easily calculated. In an associative array, each element in the array will have a unique index and value. The associative form of the foreach loop takes this into account by indicating two variables. The first variable holds the index. The second variable refers to the value associated with that index. Inside the loop, you can refer to the current index and value using whatever variable names you designated in the foreach structure. Each time through the loop, you will be given a name/value pair. In this example, the name will be stored in the variable $country, because all the indices in this array are names of countries. Each time through the loop, $country will have a different value. In each iteration, the value of the $capital variable contains the array value corresponding to the current value of $country.

TRAP

Unlike traditional arrays, you cannot rely on associative arrays to return in any particular order when you use a foreach loop to access elements of the array. If you need elements to show up in a particular order, you'll need to call them explicitly.