Skip to Content
Learn
Associative Arrays
Printing Associative Arrays

As with ordered arrays, using echo to print an entire associative array is not very useful:

$grades = [ "Jane" => 98, "Lily" => 74, "Dan" => 88, ]; echo $grades; // Prints: Array

We can combine each of the values contained by the array into a single string and use echo to print that:

echo implode(", ", $grades); // Prints: 98, 74, 88

A problem with this technique is that it only displays the values. We don’t see the keys in the array or the relationships between the keys and values. To display this information, we can use the built-in print_r() function:

print_r($grades);

The above code will produce the following output:

Array ( [Jane] => 98 [Lily] => 74 [Dan] => 88 )

Let’s print some associative arrays!

Instructions

1.

You’re going to construct an array of the top grossing movies of September 1999 and how much money they made. Name your array $september_hits. The array should have the following key => value pairs:

  • The key "The Sixth Sense" should point to the value 22896967.
  • The key "Stigmata" should point to the value 18309666.
  • The key "Blue Streak" should point to the value 19208806.
  • The key "Double Jeopardy" should point to the value 23162542.

You can use any method you’d like to construct this array.

2.

Use the echo and the implode() function to print the values in $september_hits. You can use any characters you’d like to join the array elements.

3.

Use the print_r() function to print $september_hits.

Folder Icon

Take this course for free

Already have an account?