Reputation: 1033
I'm trying to get a new to fire the first time in my loop and then after 4 counts close the and then open a new in my loop i tried doing this with modulus but i don't think I am doing it correctly.
Code I tried:
<?php for($i = 1; $i <= 12; $i++): ?>
<?php if(! (i % 4)): ?>
<div class="row">
<?php endif; ?>
<?php echo $i; ?>
<?php if(! (i % 5)): ?>
</div>
<?php endif; ?>
<?php endfor; ?>
So my results should be:
<div class="row">
1 2 3 4
</div>
<div class="row">
5 6 7 8
</div>
<div class="row">
9 10 11 12
</div>
etc...
Upvotes: 1
Views: 3439
Reputation: 401022
The simplest solution would be to :
$i % 4 == 3
, putting both an after and a before markers
For example, something like this portion of code :
$arr = range(1, 15);
echo "before";
for ($i=0 ; $i<count($arr) ; $i++) {
echo " $i ";
if ($i % 4 == 3) {
echo 'after</br />';
echo 'before';
}
}
echo "after<br />";
Will give that kind of output :
before 0 1 2 3 after
before 4 5 6 7 after
before 8 9 10 11 after
before 12 13 14 after
Advantage of this solution : you do not have to deal with any specific case (beginning and end of the loop) inside the loop.
Upvotes: 3
Reputation: 5504
You'll get mismatches the way you're doing it. What you want is probably something like:
<div class="row">
<?php for($i = 1; $i <= 12; $i++): ?>
<?php if(! (i % 4)): ?>
</div>
<div class="row">
<?php endif; ?>
<?php echo $i; ?>
<?php endfor; ?>
</div>
Upvotes: 0
Reputation: 33901
This should work, you're getting confused with how %
works, you only ever want to use % 4
(since you're checking multiples of 4), but compare against different values. !($i % 4)
will be true for exact multiples of 4, which is not what you want there.
<?php for($i = 1; $i <= 12; $i++):
if(i % 4 == 1): ?>
<div class="row">
<?php endif;
echo $i; ?>
<?php if(i % 4 == 0): ?>
</div>
<?php endif;
endfor; ?>
Upvotes: 2