PHP - Associative Arrays

Drupal loves arrays.  To maximize your Drupal coding, you need to understand arrays, specifically associative arrays.

A typical php array is coded like this:

$LearnTheBlueDrop = array('website', 'drupal', 80, 'Gary Coleman');

As you know, each memory slot in the array is accessed via a numeric index.   If you were to print the value of the second index

echo  $LearnTheBlueDrop[1];

You would get: drupal

​But Drupal takes it to a whole new level.  Drupal uses associative arrays.  Associative arrays are the same as index arrays but they have a key pair.  Using associative arrays, the index array from the first example would be rewritten like this:

$LearnTheBlueDrop = array (
    'type' => 'website',
    'webengine' => 'drupal',
    'port' => 80,
    'Eighties actor' => 'Gary Coleman',
);

Now if want to print or use a value in the keys, reference that key.

echo $LearntheBlueDrop['webengine'];

This would print:  drupal

​Note:  the last element in your associative array must have a trailing comma!

If you want to add another element to your associative array, it is simple.

$LearntheBlueDrop['carpet'] = 'green';

This would add another element in the associative array with the key named carpet with a value of green.

Ready to learn more?  Check out multidimensional arrays!