Create A Web Colour Pallette With PHP

Use the following bit of code to create a web safe colour table. In order to for the name of each colour to be displayed the background colour array is reversed and used to create the foreground colours. This makes white text appear on black backgrounds and visa-versa, the only problem is that in the middle of the table it will display grey on grey.

$bclr = array('00','11','22','33','44','55','66','77','88','99','AA','BB','CC','DD','EE','FF');
$fclr = array_reverse($bclr);
echo '<table>';
for ($i=0;$i<16;++$i) {
 for ($j=0;$j<16;++$j) {
  echo '<tr>';
  for ($k=0;$k<16;++$k) {
   $bcolor = '#'.$bclr[$i].$bclr[$j].$bclr[$k];
   $fcolor = '#'.$fclr[$j].$fclr[$j].$fclr[$j];
   echo '<td style="background-color: '.$bcolor.';color:'.$fcolor.';">'.$bcolor.'</td>';
  }
 echo '</tr>';
 }
}
echo '</table>';

I did try to do this using all of the colours, not just the web safe colours. However, this creates a table with 16,777,216 cells, which simply makes the browser fall over due to the amount of memory required.

$bclr = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
$fclr = array_reverse($bclr);
$length = count($bclr);
echo '<table>';
for ($a=0;$a<$length;++$a) {
 for ($b=0;$b<$length;++$b) {
  echo '<tr>';
  for ($c=0;$c<$length;++$c) {
   for ($d=0;$d<$length;++$d) {
    for ($e=0;$e<$length;++$e) {					
     for ($f=0;$f<$length;++$f) {
      $bcolor = '#'.$bclr[$a].$bclr[$b].$bclr[$c].$bclr[$d].$bclr[$e].$bclr[$f];
      $fcolor = '#'.$fclr[$a].$fclr[$b].$fclr[$c].$fclr[$d].$fclr[$e].$fclr[$f];
      echo '<td style="background-color: '.$bcolor.';color:'.$fcolor.';">'.$bcolor.'</td>';
     }
    }
   }
  }
 echo '</tr>';
 }
}
echo '</table>';

You can try this out if you want with a smaller array, make the colour array something like.

$bclr = array('0','6','C','F');

This creates a table with 4,096 cells, which is much more manageable than over 16 million.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.