Associative arrays in PHP

An associative array is an array that use keys instead of index numbers for each element in the array. Keys in the array are given a value. Keys can only be used once in the array. The syntax looks like this:

$array = array("key"=>value,"anotherkey"=>value);

To access an element in the associative array, you access it by its key (not its index). For example, $array[“key”]; instead of $array[0];

Watch the video below to see how you can create and use associative arrays and then scroll down to view the sample code.

Sample PHP code:

<?php
  // Associative arrays are arrays that use keys instead of index numbers
  // Every key has a value. Keys can only be used once.
  $ages = array("Jim"=>25,"Sam"=>18,"Alice"=>19,"Sarah"=>23);
  $echo $ages["Jim"]; // will echo Jim's age value
  print_r($ages); // will print all keys in the array and their values
?>