PHP Associative Array Example

This page shows how to use PHP's arrays.

//there are two types of arrays: "regular" arrays and associative arrays
//this example shows how to create an associative array
//think of an associative array as just a list key/value pairs
		

Defining Arrays

You define an associative array using PHP's built-in array() function, and supplying it with a list of key=>value pairs

$arrGrades = array("Tandi"=>"A", "Jack"=>"A", "Susan"=>"B", "Donny"=>"C", "Michaela"=>"C", "Joshua"=>"F");
		

Debugging the Contents of Arrays

You can easily output the raw contents of any array using PHP's built-in print_r() function:

print_r($arrGrades);
		
Array
(
    [Tandi] => A
    [Jack] => A
    [Susan] => B
    [Donny] => C
    [Michaela] => C
    [Joshua] => F
)

Looping Through Arrays

you can loop through the contents of an array easily by using PHP's foreach() statement:

foreach ($arrGrades as $personName => $grade) {
	echo $personName . " got a " . $grade . " in the class<br />";
}
	
Tandi got a A in the class
Jack got a A in the class
Susan got a B in the class
Donny got a C in the class
Michaela got a C in the class
Joshua got a F in the class

Accessing an Individual Element in an Associative Array

Associative arrays are indexed by any key you specified when the array was defined

So $arrGrades['Susan'] will hold the value associated with the key 'Susan'.

Susan's grade is: B