Create Associative Arrays

Unlike Numerically Indexed arrays, you can 'associate' any key or index with a value by creating Associative arrays.

Here's a quick glimpse of what that means:

php:


<?php
  //  ASSOCIATIVE array example
  $favourite = array(
    'OS'=>'Windows',
    'Forum'=>'phpBB',
    'Person'=>'Jay'
  );
?>


The array $favourite now only includes 3 values, however, unlike Numerically Indexed arrays, the 'keys' were defined by the programmer i.e. OS, Forum and Person.

In a numerically indexed array, we didn't assign the 'key' (which would have been 0, 1,2) because the default index is given by PHP automatically.

Just so that you are clear on the meaning of the word key here, let's see that example again if we had to create a Numerically Indexed array with those same values and hopefully things will get a bit clearer for you.

php:


<?php
  //  NUMERICALLY INDEXED array example
  $favourite = array( 'Windows', 'phpBB', 'Jay' );
?>


Create an Associative array

To create an Associative Array, you can do either:

php:


<?php

//  METHOD I
//  ========
$age = array( 'Asantha'=>18, 'Ruvini'=>16, 'Asitha'=>5 );

//  METHOD II
//  =========
$age['Asantha'] = 18;
$age['Ruvini'] = 16;
$age['Asitha'] = 5;

//  METHOD III
//  ==========
$age = array( 'Asantha'=>18 );
# you can do some other php stuff
# before returning to populate your
# Associative array
$age['Ruvini'] = 16;
$age['Asitha'] = 5;

?>


Each method shown above will return the array $age with 3 values.

I have NOT been writing PHP scripts for long but so far, I have rarely had the need to use Associative Arrays in my scripts. I get away with using either Numerically Indexed arrays or Multidimensional arrays (which is simply fantastic for anything you want to do if you get over the initial confusion).

TOP

How old are you?

 Teenager

 20 something

 30 something

 40 something

 Over 50