Basic TutorialsBasic Tutorials
Alternating Colors
This piece of code will require you to fill out an array of colors. Then the colors may be used in many ways if you can try to understand the basic code. Here I will demonstrate the use of them in a table.
Back
This piece of code will require you to fill out an array of colors. Then the colors may be used in many ways if you can try to understand the basic code. Here I will demonstrate the use of them in a table.
<?php
// give me an array of colors
$array_of_colors = array (
0=> "#800000",
1=> "#C00000",
2=> "#FF4040",
3=> "#FF8080",
4=> "#FFC0C0"
); // do not end the last one with comma
// here's my code, I will explain along the way
// find the total number of colors
$total_colors = count($array_of_colors);
// now say you have a table of values. you don't know how
// big the table will be. Here I will just say it has
// 30 rows.
$pretend_rows = 30;
// print a table
echo "<table width=\"350\">";
// in a loop let's do
for($i = 0; $i < $pretend_rows; $i++) {
// the bgcolor is figured out by the remainder of
// the row number divide by the total number of colors
$remainder = $i % $total_colors;
// whatever the value is
$bgcolor = $array_of_colors[$remainder];
echo "<tr><td bgcolor=\"$bgcolor\">I'm number $i</td></tr>";
} // end of the for loop
// print the end of the table
echo "</table>";
?>
Save it as alt_colors.php. Let's see the result. If you just want to do tables, just edit the color array and modify the table code. You may change the line:
echo "<tr><td bgcolor=\"$bgcolor\">I'm number $i</td></tr>";to something else more fitting. Like
// I think you might want the index to begin with 1? $index = $i + 1; echo "<tr><td bgcolor=\"$bgcolor\">#$index</td> <td bgcolor=\"$bgcolor\">another cell</td><td bgcolor=\"$bgcolor\">and another!! WOOHOO</td> </tr>";In additon, you may delete extra colors if you want less colors and of course add more if you wish to have more colors. Just don't forget that DO NOT end your last line with comma. For example, let me change the line:
// give me an array of colors $array_of_colors = array ( 0=> "#800000", 1=> "#C00000", 2=> "#FF4040", 3=> "#FF8080", 4=> "#FFC0C0" ); // do not end the last one with commato
// give me an array of colors $array_of_colors = array ( 0=> "#FF40FF", 1=> "#FF80FF", 2=> "#FFC0FF" ); // do not end the last one with commaLet's see the new result.
Back
Scripts and tutorials © 2003 - 2013 by Ying Zhang. No redistribution without permission!