Skip navigation.
Appendix D will help with debugging your code

Chapter 12 Hints and Help

QUESTION: I'm having trouble with Code Completion exercises 4, 5 or 7, that use associative arrays as lookups. How do I look up a value in an associative array?

ANSWER: In the travelCosts exercise you are looking up a destination in the $airfare and $hotel arrays. In the scenes exercise you are looking up a direction in the $scenes array.

Look at pages 446 and 447 to see how to use a variable as the index of an associative array to lookup a value in the array. For example you could look up an associative array that contains the capitals of countries using something like $capitals["Spain"] to get "Madrid". But you could also use a variable as your lookup. If the user had selected a country and this is stored in a variable named $country, you could look up the capital in the $capitals array using $capitals[$country].

Here's another example. Let's say you have an associative array named $myDogs where the index values are the dog names and the values in each element are the ages of each dog:

$myDogs ['Rex'] = 2;
$myDogs ['Lucy'] = 5;

You can of course obtain the age of Lucy by referring to $myDogs ['Lucy'] in your code, for example:

print ("<p>Lucy is ".$myDogs ['Lucy']." years old.</p>");

But what if you want to choose which dog's age to use if the dog's name is stored in a variable (for example if the user selected the dog from a drop down list)? You can use the variable as the index value to select the dog you want from the array, for example, if the dog's name is stored in a variable named $dogName:

print ("<p>$dogName is ".$myDogs[$dogName]." years old.</p>");

Be sure that the value stored in $dogName is the same case as the name used as the array index.