It is often easier to use an array if the key is a string rather than a number. For example, an array of state capitals would be easier to use if the key was the state name. An associative array is an array that uses a string instead of number in the square brackets as a key. Like numeric arrays, you can create an associative array by assigning a member to it with an array operator or with an a array statement but the syntax is a little different.
The following example creates an array named $state_capitals by adding five members to it using the array operator then uses the key, "California" to output the string, "Sacramento":
<?
$state_capitals[Alabama] = "Montgomery";
$state_capitals[Alaska] = "Juneau";
$state_capitals[Arizona] = "Phoenix";
$state_capitals[Arkansas] = "Little Rock";
$state_capitals[California] = "Sacramento";
echo $state_capitals['California'];
# outputs Sacramento
?>
The next example creates the same array but uses an array statement :
<?
$state_capitals = array(
"Alabama" => "Montgomery",
"Alaska" => "Juneau",
"Arizona" => "Phoenix",
"Arkansas" => "Little Rock",
"California" => "Sacramento", );
echo $state_capitals['California'];
# outputs Sacramento
?>
The members do not have to be added alphabetically. PHP has sorting functions if you want to output an array alphabetically. The spaces I used to indent the elements is just to make the code easier to read and is not required.
|
|
|