How to Display all of the Elements of an Associative Array in PHP


In this article, we show how to display all of the elements of an associate array in PHP.

To display all of the elements of an array in PHP, the foreach function is used. We use the foreach function with the keyword as and then use the statement $key => $value as the pair to show each part that makes up each element, the key and the value assigned to the key. This way, when the foreach function goes through each element of the array, we can display either the key of the array, or the value, or both, if we want.

Now, let's create an array and then go over the coding of how to display it:

$Eye_color= array();
$Eye_color['John']= 'Blue';
$Eye_color['Steve']= 'Brown';
$Eye_color['Michelle']= 'Green';

We've now created an associative array. The keys of the array are 'John', 'Steve', and 'Michelle'. The values of the array are 'Blue', 'Brown', and 'Green'.

Displaying the Entire Array

To display all of the elements of an associative array, we use the general format:

foreach ($array_name as $key => $value) {
echo "$key = $value <br>";

You can modify the echo statement output anything you want. But if want the output of all the elements in the form of key = value, the above code is used.

The PHP code, then, to display all of the elements of the above array which we have created would be:

PHP Output

John = Blue
Steve = Brown
Michelle = Green

HTML Comment Box is loading comments...