PHP Associative Arrays

An associative array is similar to an indexed array except that instead of using numbers to refer to each item, a label, which is commonly a string, is used instead. Therefore, associative arrays are made up of a series of key-value pairs.

Both arrays have their place. Indexed arrays are designed to maintain order, whereas associative arrays provide an easy to remember label for accessing the values inside. If the order is important, use indexed arrays. If it is more important to easily retrieve specific information without worry about order, use an associative array.

Creating an Associative Array

Associative arrays, just like indexed arrays, can be created using the array() function or the short array syntax. However, instead of just providing a list of values, a list of labels and values needs to be provided.

Retrieving values from an associative array is similar to index arrays, but instead of using the numbered index, the label is used.

<?php 
  // creating an assoc array
  $assoc = [
    "first_name" => "Kevin",
    "last_name" => "Skoglund"
  ];

  // get the first name
  echo $assoc["first_name"]; // Kevin
?>

NOTE

Using numbers on an associative array will not work unless a number is specifically provided as a label.

<?php 
  // creating an assoc array
  $assoc = [
    "first_name" => "Kevin",
    "last_name" => "Skoglund"
  ];

  // attempting to get first name by index
  var_dump($assoc[0]); // NULL
?>

Updating an Associative Array

Updating an associative array is also similar to an indexed array. It is possible to assign a new value to an existing label, as well as creating new labels and values after the array has been defined.

<?php 
  // creating an assoc array
  $assoc = [
    "first_name" => "Kevin",
    "last_name" => "Skoglund"
  ];

  // assign new value to first name
  $assoc["first_name"] = "Larry";

  // adding age to the array
  $assoc["age"] = 33;
?>