Skip navigation.
Appendix D will help with debugging your code

Chapter 11 Hints and Help

QUESTION: I'm having trouble getting the correct result for Modify5 but I'm sure my code is right!

ANSWER:A common mistake in Modify5 is to use the same variable name for the variable being used to read each line from the file as the name already being used for the array. Since the array is named $income be sure to use a different name for the variable that is reading each line from the file.

QUESTION: Code Exercise 3 asks me to calculate the count of orders for more than one bush but doesn't explain how to display this. The code template already includes print statements that display the sum and the count of ALL orders. Should I add a THIRD print statement to display the count of all orders for more than one bush?

ANSWER:The wording of the exercise is unclear. Yes, you will need to add a third print statement to display the count of all orders for more than one bush.

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 385 and 386 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.