PHP modulus function not give me expected results

58 Views Asked by At

I am trying to work out how to use the modulus function in PHP with this simple example using a WordPress loop I am wanting to echo out a message every 1, 2 and 3rd iterations of the loop...

if ( $the_query->have_posts() ) {

    $counter = 0;

    while ( $the_query->have_posts() ) {

        $counter++;

        $the_query->the_post();

        if ($counter % 1 == 0) {
            
            $output .= '1 - ' . $counter . '<br />------------<br />';

        } elseif ($counter % 2 == 0) {

            $output .= '2 - ' . $counter . '<br />------------<br />';

        } elseif ($counter % 3 == 0) {

            $output .= '3 - ' . $counter . '<br />------------<br />';

        }

    }
   
}

I am seeng this when I run it thoughh..

1 – 1
————
1 – 2
————
1 – 3
————

Can anyone tell me why I am seeing these results? I was expecting to see the echo 1 2 and 3 be output for the 1st second and third row.

2

There are 2 best solutions below

0
terence-john On

Every time you divide an integer by one there is no remainder!

Therefore the line

if ($counter % 1 == 0)

is always true!

0
Gunaraj Khatri On

Because it always satisfy first condition:

// no matter what value is $counter , it always satisfy that the given value is always divisible by 1 and hence remainder will be 0 

if ($counter % 1 == 0) {
            
            $output .= '1 - ' . $counter . '<br />------------<br />';
``
That's why it don't go for other conditions