Home > Articles > Data > MySQL

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

Read PHP and MySQL® Web Development, Fourth Edition or more than 24,000 other books and videos on Safari Books Online. Start a free trial today.



Associative Arrays

In the products array, we allowed PHP to give each item the default index. This meant that the first item we added became item 0, the second item 1, and so on. PHP also supports associative arrays. In an associative array, we can associate any key or index we want with each value.

Initializing an Associative Array

The following code creates an associative array with product names as keys and prices as values.

$prices = array( 'Tires'=>100, 
'Oil'=>10, 'Spark Plugs'=>4 );

Accessing the Array Elements

Again, we access the contents using the variable name and a key, so we can access the information we have stored in the prices array as $prices[ 'Tires' ], $prices[ 'Oil' ], and $prices[ 'Spark Plugs' ].

Like numerically indexed arrays, associative arrays can be created and initialized one element at a time.

The following code will create the same $prices array. Rather than creating an array with three elements, this version creates an array with only one element, and then adds two more.

$prices = array( 'Tires'=>100 );
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;

Here is another slightly different, but equivalent piece of code. In this version, we do not explicitly create an array at all. The array is created for us when we add the first element to it.

$prices['Tires'] = 100;
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;

Using Loops with Associative Arrays

Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop or the list() and each() constructs.

The foreach loop has a slightly different structure when using associative arrays. We can use it exactly as we did in the previous example, or we can incorporate the keys as well:

foreach ($prices as $key => $value)
 echo $key.'=>'.$value.'<br />';

The following code lists the contents of our $prices array using the each() construct:

while( $element = each( $prices ) )
{
 echo $element[ 'key' ];
 echo ' - ';
 echo $element[ 'value' ];
 echo '<br />';
}

The output of this script fragment is shown in Figure 3.2.

Figure 3.2Figure 3.2 An each() statement can be used to loop through arrays.

In Chapter 1, we looked at while loops and the echo statement. The preceding code uses the each() function, which we have not used before. This function returns the current element in an array and makes the next element the current one. Because we are calling each() within a while loop, it returns every element in the array in turn and stops when the end of the array is reached.

In this code, the variable $element is an array. When we call each(), it gives us an array with four values and the four indexes to the array locations. The locations key and 0 contain the key of the current element, and the locations value and 1 contain the value of the current element. Although it makes no difference which you choose, we have chosen to use the named locations, rather than the numbered ones.

There is a more elegant and more common way of doing the same thing. The function list() can be used to split an array into a number of values. We can separate two of the values that the each() function gives us like this:

$list( $product, $price ) = each( $prices );

This line uses each() to take the current element from $prices, return it as an array, and make the next element current. It also uses list() to turn the 0 and 1 elements from the array returned by each() into two new variables called $product and $price.

We can loop through the entire $prices array, echoing the contents using this short script.

while ( list( $product, $price ) = each( $prices ) )
 echo "$product - $price<br />";

This has the same output as the previous script, but is easier to read because list() allows us to assign names to the variables.

One thing to note when using each() is that the array keeps track of the current element. If we want to use the array twice in the same script, we need to set the current element back to the start of the array using the function reset(). To loop through the prices array again, we type the following:

reset($prices);
while ( list( $product, $price ) = each( $prices ) )
 echo "$product - $price<br />";

This sets the current element back to the start of the array, and allows us to go through again.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus