Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

All code examples must follow the Markdown rules as this site uses Markdown. If you don't know how, click here for a tutorial. Any code examples not using Markdown will be deleted.
All code examples must follow the Markdown rules as this site uses Markdown. If you don't know how, click here for a tutorial. Any code examples not using Markdown will be deleted.

Modulo Operator

So, I'm back to my beginning php programming course. I think I may have run into this and posted about it on the old forum a long time ago. But I want to ask again here on the new forum.

My little snippet of code is to output the numerals 1 - 10. But also to differentiate odd and even numbers. So I used the modulo operator. What I expected to happen was for all even numerals to print in bold. But what happened is that all ODD numbers print in bold. I don't understand why. If an odd number is divided by 2 there will be a remainder. If an even number is divided by 2 there will be no remainder. So I'm obviously not understanding how the modulo operator... well, operates.

My code snippet:

<?php
    $count = 1;
    while($count <= 10) {
        if($count % 2) {
            echo "<b>{$count}, </b>";
        }
            else {
            echo $count . ", ";
        }
        $count ++;
    }
?>

What it's printing:

1 2 3 4 5 6 7 8 9 10

Comments

  • As I usually do, I asked a question before really thinking about it.

    My problem is obvious...

    if ($count % 2)
    

    What? If $count % 2 what? Oh, idiot!

    if ($count % 2 == 0)
    

    If $count % 2 has no remainder, the number is EVEN. Doh!

    data66
  • edited August 2016
    The user and all related content has been deleted.
  • I wanted the even numerals to print in bold. That's why the bold tags.

    (I feel honored that your first post on the new forum was in reply to my question!! :smiley: )

    data66
  • The user and all related content has been deleted.
Sign In or Register to comment.