Wednesday, May 18, 2011

PHP - Alternate color divs using variable variables in a loop

If writing repetitive code, it is simple to instead loop thorugh an array, repeating the same code for each value. But to style it in a more interesting way than it all being the same, variable variables can be used to alter the style at each iteration of the loop...


<?php
$array = array("value one", "value two", "value three");
$color1="#e92e27";
$color2="#507FF7";
$color3="#e8e507";

$i="1";

foreach($array as $val)
{
if($i==4){$i="1";}

echo "<div style='width:150px;border:4px ".${color.$i}." solid;background-color:#ffffff;margin:5px;padding:5px;'>";

echo $val;

echo "</div>";
$i++;
}
?>

Any number of colors and any number of values can be added. This is useful if the list of values is long.

The result of the above code would look like this....



value one


value two


value three

No comments: