I have some php code below, where I’m using foreach.
<div class="carousel-inner">
<?php if(count($items)): ?>
<?php foreach($items as $key=>$item) : ?>
<div class="item <?php echo ($key%2) ? "active" : ""; ?>">
<?php
$extra_imagefilename = md5("Image".$item->id);
$extra_imagepath = 'media/k2/items/src/'.$extra_imagefilename.'.jpg';
preg_match_all('/img src="([^"]+)"/i', $item->introtext . $item->fulltext, $matches); ?>
<?php if(@file_exists($extra_imagepath)) { ?>
<img src="<?php echo $extra_imagepath; ?>" style="alt="<?php echo $item->title; ?>" title="<?php echo $item->title; ?>" />
<?php } ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
I need the 1st div that appears to have a class called “item active” and all other div classes in the foreach to have a class of “item”.
Where have I gone wrong with the below code?
<?php if(count($items)): ?>
<?php foreach($items as $key=>$item) : ?>
<div class="item <?php echo ($key%2) ? "active" : ""; ?>">
Any help/advice would be really appreciated.
Thanks
($key%2) ? "active" : "";will outputactivefor any$keythat is not divisible by 2. See Wikipedia’s page about the modulo operation.Assuming you use numeric indexes for
$itemand they are consecutive starting with0you can just writeto have the first
divhave theclassactive.If you don’t know about the values of
$keyyou could just use a flag:On the first run
$firstwill betrueand yourdivgets it’s classactive. On any other run it will befalse.