I would like to output some specific HTML on the third iteration of a loop in PHP. Here is my code:
<?php foreach ($imgArray as $row): ?>
<div class="img_grid"><?= $row ?></div>
<?php endforeach; ?>
On the third iteration of this loop, Instead of displaying:
<div class="img_grid"><?= $row ?></div>
I would like to display:
<div class="img_grid_3"><?= $row ?></div>
I would like to end up with this if my array looped 8 times:
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid_3">[some html]</div>
<div class="img_grid">[some html]</div>
<d开发者_运维知识库iv class="img_grid">[some html]</div>
<div class="img_grid_3">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
Thanks
Assuming $imgArray
is an array and not an associative array (i.e. it has numeric indices), this is what you want:
<?php foreach($imgArray as $idx => $row): ?>
<?php if($idx % 3 == 2): ?>
<div class="img_grid_3"><?php echo $row; ?></div>
<?php else: ?>
<div class="img_grid"><?php echo $row; ?></div>
<?php endif; ?>
<?php endforeach; ?>
You could tighten it up a bit like this:
<?php foreach($imgArray as $idx => $row):
if($idx % 3 == 2) {
$css_class = 'img_grid_3';
} else {
$css_class = 'img_grid';
}
?>
<div class="<?php echo $css_class; ?>"><?php echo $row; ?></div>
<?php endforeach; ?>
Or even more (some folks would just go with a ternary conditional inline in the HTML), but the law of diminishing returns kicks in eventually with regard to readability. Hopefully this gives you the right idea, though.
精彩评论