Create A Web Colour Pallette With PHP

29th April 2008 - 2 minutes read time

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.

  1. $bclr = array('00','11','22','33','44','55','66','77','88','99','AA','BB','CC','DD','EE','FF');
  2. $fclr = array_reverse($bclr);
  3. echo '<table>';
  4. for ($i=0;$i<16;++$i) {
  5. for ($j=0;$j<16;++$j) {
  6. echo '<tr>';
  7. for ($k=0;$k<16;++$k) {
  8. $bcolor = '#'.$bclr[$i].$bclr[$j].$bclr[$k];
  9. $fcolor = '#'.$fclr[$j].$fclr[$j].$fclr[$j];
  10. echo '<td style="background-color: '.$bcolor.';color:'.$fcolor.';">'.$bcolor.'</td>';
  11. }
  12. echo '</tr>';
  13. }
  14. }
  15. 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.

  1. $bclr = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
  2. $fclr = array_reverse($bclr);
  3. $length = count($bclr);
  4. echo '<table>';
  5. for ($a=0;$a<$length;++$a) {
  6. for ($b=0;$b<$length;++$b) {
  7. echo '<tr>';
  8. for ($c=0;$c<$length;++$c) {
  9. for ($d=0;$d<$length;++$d) {
  10. for ($e=0;$e<$length;++$e) {
  11. for ($f=0;$f<$length;++$f) {
  12. $bcolor = '#'.$bclr[$a].$bclr[$b].$bclr[$c].$bclr[$d].$bclr[$e].$bclr[$f];
  13. $fcolor = '#'.$fclr[$a].$fclr[$b].$fclr[$c].$fclr[$d].$fclr[$e].$fclr[$f];
  14. echo '<td style="background-color: '.$bcolor.';color:'.$fcolor.';">'.$bcolor.'</td>';
  15. }
  16. }
  17. }
  18. }
  19. echo '</tr>';
  20. }
  21. }
  22. 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.