Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;  ?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading