PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 17, 2022

[FIXED] if condition for array index

 February 17, 2022     arrays, indexed, php, wordpress     No comments   

Issue

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;  ?>


Answered By - BenM
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,913

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing