Jump to content

Every 3rd iteration of a loop


pealo86

Recommended Posts

To solve a bigger issue I'm having in WordPress, I have thrown together this basic script in PHP script to help me get to the bottom of it.

 

Basically, I am trying to add a <hr /> tag after every 3rd paragraph:

http://www.mattpealing-server.co.uk/~freshmat/wp-content/themes/match2move/test.php

 

With the following code:

<?php $count = 0; ?>

 

<?php while($count < 20) : ?>

 

<span>

<p><strong><?php echo $count; ?>:</strong> Lorem ipsum dolor sit amet, consectetuer adipiscing.</p>

</span>

 

<?php if ($count % 3) : ?><hr /><?php endif; ?>

 

<?php $count ++; ?>

 

<?php endwhile; ?>

 

However if you notice, this output just doesn't turn out like this! Does the operator I'm using not test if $count is a multiple of 3?

Link to comment
https://forums.phpfreaks.com/topic/250773-every-3rd-iteration-of-a-loop/
Share on other sites

To test if its a multiple of 3 you have to test whether the modulus of the count and number are equal to 0.

In your comparison I added 1 to the count since your starting your count at 0 not 1, every 3 item is 2, 5, 8, etc....

 

Please use code tags...its easier for people trying to help you that way.

<?php $count = 0; ?>
<?php while($count < 20) : ?>
<span><p><strong>
<?php echo $count; ?>:
</strong> Lorem ipsum dolor sit amet, consectetuer adipiscing.</p></span>
<?php if (($count+1) % 3 == 0) : ?>
	<hr />
<?php endif; ?>
<?php $count ++; ?>
<?php endwhile; ?>

No need to add 1 to the count, just use the correct comparison

if (($count) % 3 == 2)

 

But, better yet, you should make the number of records to separate a variable so you can change it by just changing the variable and not having to modify code. The same goes for the number of records to show. Don't hard code the 20, make it a variable.

<?php

$record_count = 20;
$record_grouping = 3;

for($count=0; $count<$record_count, $count++)
{
    echo "<span><p><strong>$count</strong> Lorem ipsum dolor sit amet, consectetuer adipiscing.</p></span>\n";
    if (($count % $record_grouping) == $record_grouping-1)
    {
        echo "<hr />\n";
    }
}

?>

Wow I have no idea how that +1 got in there! The operator I was actually using was like this:

<?php if ($count % 3) : ?>

 

Which I assume is still incorrect.

 

I've updated it now to

<?php if (($count) % 3 == 2) : ?>

 

And it's working fine. I see what you mean about the variables, however the number of loop iterations is actually taken care of by WordPress in my real-life situation, but I'll definiately keep it in mind.

 

Thanks for the help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.