Working with Associative Arrays - Exercise

Contact Us or call 1-877-932-8228
Working with Associative Arrays - Exercise

Working with Associative Arrays

Duration: 10 to 15 minutes.

In this exercise, you will use arrays to create a table with two columns that lists all your favorite colors and their hexadecimal equivalents. The background of each table row should be the same as the color named in the row as shown in the screenshot below.Two-Column Color Table

  1. Open Arrays/Exercises/ColorTable2.php for editing.
  2. Create an associative array that holds color hex codes indexed by their color names, which can be found at http://www.w3schools.com/html/html_colornames.asp.
  3. After the existing table row, write code to loop through the array outputting a table row with two columns for each element in the array.
  4. Test your solution in a browser.

Solution:

Arrays/Solutions/ColorTable2.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Color Table</title>
</head>

<body>
<h1>Color Table</h1>
<?php
	$favColors = array();
	$favColors['BlanchedAlmond'] = '#ffebcd';
	$favColors['CadetBlue'] = '#5f9ea0';
	$favColors['BurlyWood'] = '#deb887';
	$favColors['DarkOliveGreen'] = '#556b2f';
	$favColors['HotPink'] = '#ff69b4';
	$favColors['Papayawhip'] = '#ffefd5';
?>

<table border="1">
<tr>
	<th>Color Name</th>
	<th>Hex Code</th>
</tr>
<?php
	foreach ($favColors as $key => $item)
	{
		echo "	<tr bgcolor='$key'>
					<td>$key</td>
					<td>$item</td>
				</tr>";
	}
?>
</table>
</body>
</html>
Next