PHP logic to add a class to 2 rows every other 2 rows

164 Views Asked by At

Can anyone help me with the logic to add a class .col-md-offset-2 to every two rows in my code below...

<?php while(have_rows('report_quotes')): the_row(); ?>

  <div class="col-md-12 <?php // help me ?>">

     <?php /* quote */ ?>
     <?php Post::get_template_part('sections/quote'); ?>

  </div>

<?php endwhile; ?>

So the output will look like this...

<div class="col-md-12">...</div>
<div class="col-md-12">...</div>
<div class="col-md-12 col-md-offset-2">...</div>
<div class="col-md-12 col-md-offset-2">...</div>
<div class="col-md-12">...</div>
<div class="col-md-12">...</div>
<div class="col-md-12 col-md-offset-2">...</div>
<div class="col-md-12 col-md-offset-2">...</div>
<div class="col-md-12">...</div>
<div class="col-md-12">...</div>
<div class="col-md-12 col-md-offset-2">...</div>
<div class="col-md-12 col-md-offset-2">...</div>
...

Can anyone help?

Thanks

3

There are 3 best solutions below

2
On BEST ANSWER

You can do this by using the modulus operator (%)

<?php $i = 0; while($i < 6): ++$i; ?>
 <div class="col-md-12 <?=in_array($i % 4, array (0,3)) ? 'col-md-offset-4' : null ?>">...</div>
<?php endwhile; ?>

So in your case -

<?php $i = 0; while(have_rows()): the_row(); ++$i; ?>
 <div class="col-md-12 <?=in_array($i % 4, array (0,3)) ? 'col-md-offset-4' : null ?>">
    <?php /* quote */ ?>
    <?php Post::get_template_part('sections/quote'); ?>
 </div>
<?php endwhile; ?>

This essentially gets the remainder for each increment and in our case we know that if the remainder is 0 (divisible by 4) or a 3, then it should be indented.

0
On

Add a pointer that keeps track of the current loop index, and check if it the 3th or the 4th one in an iteration with the modulo operator.

Like this:

<?php 
    $i = -1;
    while(have_rows('report_quotes')): the_row();
    $i++;
?>

    <div class="col-md-12
        <?php if ( ($i % 4) == 2 || ($i % 4) == 3 ) { echo 'col-md-offset-2'; } ?> ">

        <?php /* quote */ ?>
        <?php Post::get_template_part('sections/quote'); ?>

    </div>

<?php endwhile; ?>
0
On

Add a counter to know which row of the array you're in and use modulo:

<?php 
$i = 0;
while(have_rows('report_quotes')): the_row(); ?>

   <div class="col-md-12 <?php if (($i%4==2)||($i%4==3) {echo ' col-md-offset-2'; } ?> ?>">


     <?php Post::get_template_part('sections/quote'); ?>

  </div>

<?php endwhile; ?>