skip to Main Content

I am going to add limit and offset to this loop:

<?php
$images = get_field('am_c_gallery');
if( $images ): ?>
        <?php foreach( $images as $image ): ?>
          <div class="item-big"></div>
        <?php endforeach; ?>
<?php endif; ?>

How can I add offset 1 and 5 image like this to my loop in output:

   if first image:
   <div class="item-big"></div>
        
   if 2-5 images:
   <div class="item-small"></div>
   <div class="item-small"></div>
   <div class="item-small"></div>
   <div class="item-small"></div>
    
   if 5 - unlimited:
   <div class="item-hide"></div>

3

Answers


  1. Use:

    for($index = 0; $index < count($images); $index++){
       $images[$index] // first element
    }
    

    or

    foreach($images as $index => $value){
    if (0 === $index) {
      //first element
    }
    // ...
    //
    }
    

    to know the 1st, 2nd to 5th element and to make condition with.

    NB: to use foreach loop, make sure that the element of your array is not a key/value element otherwise the $index is not a number but the value of key

    Login or Signup to reply.
  2. <?php
    $images = get_field('am_c_gallery');
    if ($images) {
      $n = 0;
      foreach ($images as $image) {
        $n++;
        echo match (true) {
          ($n == 1) => '<div class="item-big"></div>',
          ($n <= 5) => '<div class="item-small"></div>',
          default => '<div class="item-hide"></div>',
        };
      }
    }
    
    Login or Signup to reply.
  3. When faced with a mathematical process which must resolve in one of three ways, I like to leverage the three-way comparison operator as a fun outside-the-box approach.

    Assuming an indexed array is being iterated, divide the indexes by 4 and round up — the result will be -1 when $i is 0, 0 when $i is 1, 2, 3, or 4, and 1 when $i is above 4.

    Using printf() and match() are clean, maintainable functions to organize the processing and displaying. I’ll admit, I don’t know what data is in $image, so that may need to be altered.

    Code: (Demo)

    foreach (get_field('am_c_gallery') ?: [] as $i => $image) {
        printf(
            '<div class="%s">%s</div>' . PHP_EOL,
            match (ceil($i / 4) <=> 1) {
                -1 => 'item-big',
                 0 => 'item-small',
                 1 => 'item-hide'
            },
            $image
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search