SoulieBaby
SoulieBaby

Reputation: 5471

php every 1st and 4th (onwards) add a class

I'm trying to change a class on a div within a foreach loop.. I need the first item to have col-md-12 and then the next two to be col-md-6 and back to the start again..

col-md-12
col-md-6 col-md-6
col-md-12
col-md-6 col-md-6
col-md-12
col-md-6 col-md-6

Here's what I've done, which isn't doing it for the first item:

<?php $j=0;foreach ($value as $item) : $linky = ''; ?>                  
    <div class="grid-item <?php if ($j % 3 == 1) : ?>col-md-12<?php else : ?>col-md-6<?php endif; ?>">
        xxx
    </div>
<?php $j++;endforeach; ?>

This is giving me

col-md-6 (i want this one to be col-md-12)
col-md-12
col-md-6 col-md-6
col-md-12
col-md-6 col-md-6

Upvotes: 1

Views: 68

Answers (1)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use the following solution using foreach:

<?php $j=0;foreach ($value as $item) : $linky = ''; ?>                  
    <div class="grid-item <?php if ($j % 3 === 0) : ?>col-md-12<?php else : ?>col-md-6<?php endif; ?>">
        xxx
    </div>
<?php $j++;endforeach; ?>

You can also use the following solution using for:

<?php for ($j = 0; $j < count($value); $j++) : $linky = ''; ?>                  
    <div class="grid-item <?php if ($j % 3 === 0) : ?>col-md-12<?php else : ?>col-md-6<?php endif; ?>">
        xxx
    </div>
<?php endfor; ?>

What is the difference between 0 and 1:

index ($j) | $j % 3 === 1 | $j % 3 === 0
----------------------------------------
         0 | false        | true
         1 | false        | false
         2 | false        | false
         3 | false        | true
         4 | true         | false
         5 | false        | false
         6 | false        | true
         7 | true         | false

Upvotes: 1

Related Questions