We can access the value that a given key points to by using square brackets (
$my_array = ["panda"=>"very cute", "lizard"=>"cute", "cockroach"=>"not very cute"]; echo $my_array["panda"]; // Prints: very cute
In the code above, we accessed the value
"very cute" using its key,
To add new elements to an associative array, we use the assignment operator (
$my_array["capybara"] = "cutest"; echo $my_array["capybara"]; // Prints: cutest
In the code above, we added a fourth key value pair to the array. We accessed the new value
"cutest" using its key
"capybara" and printed it using
The computer treats code between the square brackets as an expression, so that code will be evaluated before the array is accessed. This enables us to use variables, functions, and operators within the square brackets:
$favorites = ["favorite_food"=>"pizza", "favorite_place"=>"my dreams", "FAVORITE_CASE"=>"CAPS", "favorite_person"=>"myself"]; echo $favorites["favorite" . "_" . "food"]; // Prints: pizza $key = "favorite_place"; echo $favorites[$key]; // Prints: my dreams echo $favorites[strtoupper("favorite_case")]; // Prints: CAPS
Let’s access some elements!
We provided you with three arrays
$assignment_three. These arrays each hold students’ grades for a given assignment. Two key=>value pairs need to be added:
- Sara turned in her second assignment late—she got a 65.
- Kat’s third assignment was briefly misplaced—she got a 97.
You should complete this task without changing the code we’ve provided.
Create a new ordered array named
$dans_grades which holds Dan’s grades from each of the three assignments. To add these elements to the new array, access them from each of the provided arrays using the key
We provided you with the variable
echo to print the result of accessing
$assignment_two with the