DJ Mike's Tutorials: PHP, Associative Arrays


< ^ >

Associative Arrays

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.

Creating Associative Arrays With The Array Operator

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
?>

Creating Associative Arrays With The Array Statement

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.


< ^ >



Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>