Aryan G
Aryan G

Reputation: 1301

Alternate div inside a while loop?

I need to dispay three divs alternatively inside a while loop. The first div has the class name box-hdr5 and the second div is box-hdr4

Is there any way to do so? Please give me some idea.

Upvotes: 0

Views: 1225

Answers (3)

Asherah
Asherah

Reputation: 19347

You don't even need to do modulo by 2.

$alternate = false;
while (/* true */) {
    $alternate = !$alternate;
    if ($alternate) {
        // box-hdr4
    } else {
        // box-hdr5
    }
}

But the answers above are equally good.

Upvotes: 1

Dan Grossman
Dan Grossman

Reputation: 52372

$i = 0

while (true) {
  $class = ($i++ % 2 == 0) ? 'box-hdr5' : 'box-hdr4';
  echo "<div class='" . $class . "'>stuff</div>";
}

% is the modulus operator, which returns the remainder of integer division. The remainder will be 0 when $i is evenly divisible by 2, which will be every other time through the loop.

Upvotes: 1

deceze
deceze

Reputation: 522081

You just need to have a counter and figure out whether the number is odd or even, which is easily done with the modulus operator.

$x = 0;
while (/* true */) {
    if ($x++ % 2) {
        /* box-hdr4 */
    } else {
        /* box-hdr5 */
    }
}

Upvotes: 5

Related Questions