Associative Arrays in PHP

PHP How To

An associative array is composed of a collection of key and value pairs. Indexed array is an array with a numeric key.

images/articles/php/associative-arrays-in-php.jpg

Simple Declaration

$carParts = array( 
'Tires'=>100,
'Window'=>1042,
'DoorHandle'=>917
);

Array of Associative Arrays

public $notifyPartners = array(
array(
'name' => 'Twitter',
'tag' => 'Social Network',
'url' => ''),
array(
'name' => 'Campaign Monitor',
'tag' => 'Email Marketing',
'url' => ''),
array(
'name' => 'Sendloop',
'tag' => 'Email Marketing',
'url' => ''),
array(
'name' => 'Highrise',
'tag' => 'CRM',
'url' => '')
);

Looping Using For Each

foreach ($carParts as $key => $value) {
echo $key.'=>'.$value.'<br />';
}

Looping Using While

while ($element = each($carParts)) {
echo $element['key'];
echo ' - ';
echo $element['value'];
echo '<br />';
}