Alternate div inside a while loop?
I need to dispay three divs开发者_StackOverflow社区 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.
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 */
}
}
$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.
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.
精彩评论