How to print out associative arrays in PHP?
Associative arrays can be iterated through with a foreach loop to output values, or specific values can be accessed using keys. Here are some examples:
- Display all values of an associative array using a foreach loop.
$fruits = array("apple" => "red", "banana" => "yellow", "orange" => "orange");
foreach($fruits as $key => $value) {
echo "The color of $key is $value <br>";
}
The output is:
The color of apple is red
The color of banana is yellow
The color of orange is orange
- Access specific values using key-value pairs.
$fruits = array("apple" => "red", "banana" => "yellow", "orange" => "orange");
echo "The color of apple is " . $fruits["apple"];
Output result:
The color of apple is red
With the above method, it is easy to output the values of an associative array.