PHP Colors Display

Feature: Displaying WebSafe colors

Figure 1 -Part of the WebSafe Color Table

There is a list of 216 colors (6 Red x 6 Green x 6 Blue)which are called WebSafe. These colors are guaranteed to display and in the right hue on any web browser. The browser image on the left shows a partial listing of the WebSafe colors.

This PHP sample exercise will produce the table shown of those WebSafe colors. In the process, developers will see an example of nested for-loops and HTML table construction.

The program starts by declaring an array "hex" with six values - '00', '33', '66', '99', 'CC', 'FF' - which make up the WebSafe colors. Then a nested series of 3 for-loops iterate through all of these values, 216 in total, starting with '00'.'00'.'00' = black and ending with 'FF'.'FF'.'FF' = white. See the Cold Fusion equivalent for the same output; but using Cold Fusion's embedded tags. PHP and Cold Fusion have a number of functionality similarities but each has a unique coding style.

<title>Websafe Colors</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<body bgcolor="#000000">
$hex = array("00", "33", "66", "99", "CC", "FF");
echo "<h1><font color='#FFFFFF'>Web Safe Color Chart</font></h1><hr>";
echo "<table border='0'>";
for ($r=0; $r<count($hex); $r++){ //the red colors loop
  for ($g=0; $g<count($hex); $g++){ //the green colors loop
    echo "<tr>"; //Define a row for the six blue colors
    for ($b=0; $b<count($hex); $b++){ //iterate through the six blue colors
      $color = $hex[$r].$hex[$g].$hex[$b];
      //At this point we decide what font color to use
      if ( $hex[$r] <= "99" && $hex[$g] <= "99" && $hex[$b] <= "99"){<br>
        // Use a white font if the color is going to be fairly dark
        echo "<td width='100' bgcolor='#".$col."'><font color='#FFFFFF'><strong> ".$col." </strong></font></td>";
      } else {
        // Use a black font on the lighter colors
        echo "<td width='100' bgcolor='#".$col."'><font color='#000000'> ".$col." </font></td>";
    } //End of b-blue innermost loop
    echo "</tr>\n\r"; // close row after writing six color cells
  } //End of g-green loop
} //End of r-red outermost loop

Creating tables in PHP is required for smart formatting of output. This example shows the logical grouping - the table declaration occurs outside all the loops - then each cell is done at the inner-most loop, and the row declarations are done at the second most inner loop. Finally, the Table is closed off at the end of all the loops. Get used to this template, it will occur over and over again in your PHP coding.

Top of Page  Tutorials Home 
© Imagenation 2001-2004