coder_303 coder_303 - 7 months ago 23
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

style

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


php

<?php
$new= mysql_query("select * from tbl_news");
while ($row=mysql_fetch_array($new))
{

$x++;

$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

Use color array like below

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

$x=0;
while($row=mysql_fetch_array($new)){
    $x++;
    $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);
while($row=mysql_fetch_array($new)){
    $n = rand(0,$size_of_array-1);
    $class = $color_arrar[$n%3];
}
Comments