Penian4
Penian4

Reputation: 581

How to alternate background colour every other div in PHP

I'm currently working on creating a website with a blogging platform, and I want every other post container on the home page to alternate colours. Like light blue, then dark blue, light blue, dark blue, light blue, etc. I'm using a while loop to get 5 posts from the mysql database. Here is my code.

<?php
$sql = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 6");
$array = mysql_fetch_array($sql);
while ($array = mysql_fetch_array($sql)) {

//The php below this is the problem

$counter = 0;
$counter++;

$postcolour =  WHAT DO I PUT HERE ? 'lightblue' : 'darkblue';


?>


<div class="postcontainer" style="background-color: <?php echo $postcolour; ?>;">
</div> <?php } ?>

Upvotes: 0

Views: 2191

Answers (2)

Ry-
Ry-

Reputation: 224913

I'd just use CSS:

.postcontainer {
    background-color: lightblue;
}

.postcontainer:nth-of-type(even) {
    background-color: darkblue;
}

Here's a demo!

Upvotes: 4

Joseph Silber
Joseph Silber

Reputation: 219938

Just use modulus two:

$postcolour = $counter % 2 ? 'lightblue' : 'darkblue';

Upvotes: 4

Related Questions