Search code examples
phparrayswordpressindexed

if condition for array index


foreach($results as $result) :
 $featured_image=wp_get_attachment_url(get_post_thumbnail_id($result->ID));?>
     <div class="col-sm-6">
        <a href="javascript:;">
          <figure>
            <img src="<?php echo $featured_image ?>">
              <figcaption>
                <h2><?php echo get_the_title($result->ID) ?></h2>
                 <p><?php echo get_the_content($result->ID) ?></p>
               </figcaption>
           </figure>
        </a>
    </div>
<?php endforeach;  ?>

I want to print the first 4 results in col-6 divs and the rest in col-4 . I'am trying to match the index of arrray

if($results $key < 3) :
 <div class="col-sm-6"></div>
else :
<div class="col-sm-4"><div>
endif;

is there a way i can do this


Solution

  • Just pass the array index into the loop, and then check it against the class name when outputting, for instance:

    <?php
    foreach($results as $i => $result) :
    $featured_image=wp_get_attachment_url(get_post_thumbnail_id($result->ID));
    ?>
         <div class="col-sm-<?= ($i < 4) ? 6 : 4 ?>">
            <a href="javascript:;">
              <figure>
                <img src="<?php echo $featured_image ?>">
                  <figcaption>
                    <h2><?php echo get_the_title($result->ID) ?></h2>
                     <p><?php echo get_the_content($result->ID) ?></p>
                   </figcaption>
               </figure>
            </a>
        </div>
    
    <?php endforeach;  ?>