Learn
Associative Arrays
Accessing and Adding Elements

We access the value a given key points to 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, "panda".

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 echo.

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!

Instructions

1.

We provided you with three arrays $assignment_one, $assignment_two, $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.

2.

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 "Dan".

3.

We provided you with the variable $student_name. Use echo to print the result of accessing $assignment_two with the $student_name variable.

Folder Icon

Take this course for free

Already have an account?