coder_303 coder_303 - 2 years ago 93
PHP Question

How to give 3 different color for div's in loop in php

Trying to give 3 different color for div's in loop in php, now its working only two .how can i impliment alternative color for div.? Here what I want.

enter image description here


.redBackground { background-color:#F00; }
.blueBackground { background-color:#03F;}
.greenBackground { background-color:#6F3; }


$new= mysql_query("select * from tbl_news");
while ($row=mysql_fetch_array($new))


$class = ($x%2 == 0)? 'redBackground': 'blueBackground' ;

echo "<tr class='$class'>";

$id = $row['id'];

$news = $row['news'];

<div class="col-md-2 col-sm-12 col-xs-12 news_main_div">

<div class="md-trigger" data-modal="modal-11">
<div <?php echo "<tr class='$class'> ";?>>
<h1 style=" margin-bottom:5px;">
<strong ><?php echo $news ?></strong>
</h1></div></div><?php } ?>

Answer Source

Use color array like below

$color_array = array('whiteBackground', 'grayBackground', 'blueBackground');

    $class = $color_array[$x%3];

And in future, if you want to more color, then simply add color-class in array and change in $color_arrar[$x%n], where n=number_of_color

If you want random color, then use below code

$color_arrar = array('whiteBackground ','grayBackground ','blueBackground ');
$size_of_array = sizeof($color_arrar);
    $n = rand(0,$size_of_array-1);
    $class = $color_arrar[$n%3];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download