Search code examples
phpforeachkeyforeach-loop-container

php foreach div class issue


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


Solution

  • ($key%2) ? "active" : ""; will output active for any $key that is not divisible by 2. See Wikipedia's page about the modulo operation.

    Assuming you use numeric indexes for $item and they are consecutive starting with 0 you can just write

    <div class="item <?php echo ($key == 0) ? "active" : ""; ?>">
    

    to have the first div have the class active.

    If you don't know about the values of $key you could just use a flag:

    <?php $first = true; foreach($items as $key=>$item) : ?>      
        <div class="item <?php if ($first){echo "active"; $first = false;} ?>">
    

    On the first run $first will be true and your div gets it's class active. On any other run it will be false.