PHP: Output An Associative Array

In this article I’ll show you, how to output each element of an an assciative array in PHP. First of all, we need an associative array. In this example I’ll use an array with colors as the key and the corresponding HEX-code of this color as the value.

Let’s start! Here is the associative PHP array:

// Our associative array
$arrMembers = array(
	'Red'=>'ff0000',
	'Green'=>'00ff00',
	'Blue'=>'0000ff',
	'Yellow'=>'ffff00'
);

Now I’ll walk through the array. In order to do this, I’ll use the foreach() function in PHP. This function applies the content of the function-body to all elements of the array. During each iteration it assigns the key of the actual array element to an variable (in this example we use $key) and the corresponding value to another variable (her $val).

See the full code:

<?php
// Our associative array
$arrMembers = array(
	'Red'=>'ff0000',
	'Green'=>'00ff00',
	'Blue'=>'0000ff',
	'Yellow'=>'ffff00'
);
 
// Output each element of the array
foreach($arrMembers as $key=>$val) {
	echo 'Color: '.$key.' - HEX-Value: '.$val.'<br>';
}
?>

And here is the script in action:
‘ff0000’,
‘Green’=>’00ff00’,
‘Blue’=>’0000ff’,
‘Yellow’=>’ffff00’
);

// Output each element of the array
foreach($arrMembers as $key=>$val) {
echo ‘Color: ‘.$key.’ – HEX-Value: ‘.$val.’
‘;
}
?>

(Visited 917 times, 1 visits today)

Leave a Comment