How to Access an Associative Array in PHP
An associative array is an array of keys associated with values. Associative arrays are useful when the elements of an array are better represented using a string value instead of a numeric array index. In PHP, you can access the values of an associative array directly by placing the key in quotes inside square brackets. You can also use the "foreach" iterative statement to loop through the values in an associative array.
Instructions
-
-
1
Create a new PHP file in an editor or in the Notepad. Define an associative array. For example, type:
<?php
$fruit_colors = ("apple" => "red", "orange" => "orange", "lemon" => "yellow");
-
2
Access an element of the array directly by specifying the key. For example, type:
echo "The color of an apple is " . $fruit_colors["apple"];
-
-
3
Iterate through the array using the "foreach" statement to access each array element. For example, type:
foreach($fruit_colors as $fruit=>$color) {
echo "The color of a(n) " . $fruit . " is " . $color . "\r\n";
}
?>
-
4
Save the file and run it in a browser to ensure it functions correctly.
-
1
Tips & Warnings
Always use quotes around the key values in an associative array.