Home > Software engineering >  if condition for array index
if condition for array index

Time:01-05

foreach($results as $result) :
 $featured_image=wp_get_attachment_url(get_post_thumbnail_id($result->ID));?>
     <div >
        <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 ></div>
else :
<div ><div>
endif;

is there a way i can do this

CodePudding user response:

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 >
        <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;  ?>
  •  Tags:  
  • Related