A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table.
MyArray['CA'] = 'California'
MyArray['AR'] = 'Arizona'
Languages Focus: Associative Array
Associative arrays are also known as a dictionary or a hash table in other languages.
PHP Associative Array
Declare associative array with initial known values. You can also add to associative array. (You can just assign values without ever declaring it too!)
Syntax Example: $prices = array( 'Tires'=>100, 'Spark Plugs'=>4 );
$prices['Oil'] = 10;
echo "Tires=" . $prices['Tires'] . "<br>";
echo "Oil=" . $prices['Oil'] . "<br>";
About Associative Array
A set of unique keys linked to a set of values. Each unique key is associated with a value. Think of it as a two column table. MyArray['CA'] = 'California' MyArray['AR'] = 'Arizona'
Complete Example
Here is a complete example:
<html>
<head><title>PHP Hello World Example</title></head>
<body>
<?PHP
//Declare associative array with initial known values.
$prices = array( 'Tires'=>100, 'Spark Plugs'=>4 );
//Add to associative array. (You can just assign values without ever declaring it too!)
$prices['Oil'] = 10;
//Usage Example 1
echo "<br><br>Example 1<br>";
echo "Tires=" . $prices['Tires'] . "<br>";
echo "Oil=" . $prices['Oil'] . "<br>";
//Usage Example 2 - foreach loop with $key and $value
echo "<br><br>foreach loop<br>";
foreach ($prices as $key => $value)
echo $key.'=>'.$value.'<br />';
//
//Clear it for another use.
//
echo "<br><br>reset example<br>";
reset($prices);
$prices['Computer'] = 700;
$prices['monitor'] = 200;
$prices['mouse'] = 15;
foreach ($prices as $key => $value)
echo $key.'=>'.$value.'<br />';
?>
</body>
</html>