|[ Team LiB ]|
Numerically indexed arrays are useful for storing values in the order they were added or according to a sort pattern. Sometimes, though, you need to access elements in an array by name. An associative array is indexed with strings between the square brackets rather than numbers. Imagine an address book. Which would be easier, indexing the name field as 4 or as name?
Defining Associative Arrays with the array() Construct
To define an associative array with the array() construct, you must define both the key and value for each element. The following code creates an associative array called $character with four elements:
$character = array ( "name" => "bob", "occupation" => "superhero", "age" => 30, "special power" => "x-ray vision" );
We can now access any of the fields of $character:
The keys in an associative array are strings, but in its default error reporting state the engine won't complain if array keys aren't quoted.
Omitting quotation marks for array keys is poor practice, however. If you use unquoted strings as keys and your error reporting is set to a higher-than-standard level, the engine will complain every time such an element is met. Even worse, if an unquoted array key coincides with a constant, the value of the constant will be substituted for the key as typed.
Directly Defining or Adding to an Associative Array
You can create or add a name/value pair to an associative array simply by assigning a value to a named element. In the following, we re-create our $character array by directly assigning a value to each key:
$character["name"] = "bob"; $character["occupation"] = "superhero"; $character["age"] = 30; $character["special power"] = "x-ray vision";
|[ Team LiB ]|