Skip to Content
Learn
Associative Arrays
Associative Arrays

Associative arrays are collections of key=>value pairs. The key in an associative array must be either a string or an integer. The values held can be any type. We use the => operator to associate a key with its value. key/value pairs We can think of keys as pointing to their values since the key points the computer to the space in memory where the value is stored.

$my_array = ["panda" => "very cute", "lizard" => "cute", "cockroach" => "not very cute"];

In the code above, we created an associative array using short array syntax. $my_array has three key=>value pairs:

  • The key "panda" points to the value "very cute".
  • The key "lizard" points to the value "cute".
  • The key "cockroach" points to the value "not very cute".

We can also build associative arrays using the PHP array() function.

$about_me = array( "fullname" => "Aisle Nevertell", "social" => 123456789 );

In the code above, we created an associative array, $about_me, with two key=>value pairs:

  • The key "fullname" points to the value "Aisle Nevertell".
  • The key "social" points to the value 123456789.

Let’s make some arrays!

Instructions

1.

Use the array() function to create an array $php_array which has the following key => value pairs:

  • The key "language" should point to the value "PHP".
  • The key "creator" should point to the value "Rasmus Lerdorf".
  • The key "year_created" should point to the value 1995.
  • The key "filename_extensions" should point to the value [".php", ".phtml", ".php3", ".php4", ".php5", ".php7", ".phps", ".php-s", ".pht", ".phar"] (an ordered array).
2.

Use the short array syntax to create an array $php_short which has the same key => value pairs.

Folder Icon

Take this course for free

Already have an account?