Head Way
Head Way

Reputation: 323

I need some explanation on the percentage sign operator

I've taken this chunk of code from php.net but i need explanation on what the percentage sign is doing. I've changed the year a few times and get new results but it all seems very random.

<?php
    function getChineseZodiac($year){

        switch ($year % 12) :
            case  0: return 'Monkey';  // Years 0, 12, 1200, 2004...
            case  1: return 'Rooster';
            case  2: return 'Dog';
            case  3: return 'Boar';
            case  4: return 'Rat';
            case  5: return 'Ox';
            case  6: return 'Tiger';
            case  7: return 'Rabit';
            case  8: return 'Dragon';
            case  9: return 'Snake';
            case 10: return 'Horse';
            case 11: return 'Lamb';
        endswitch;
    }

    echo getChineseZodiac(2016);
    ?>

I've read that it's a Modulus operator and is for the remainder. Thanks in advance.

Upvotes: 1

Views: 212

Answers (2)

raidenace
raidenace

Reputation: 12836

A mod operator returns the remainder of the division.

Eg. 7 % 3 is 1 because after you divide 7 by 3 the remaining whole number is 1

In the code above

2004/12 = 167

but the reminder of the division is 0, since 2004 is perfectly divisible by 12.

So

2004 % 12 = 0

Upvotes: 7

Medo42
Medo42

Reputation: 3821

The intent here is to "wrap around" at the 12, so that you get a sequence which repeats every 12 years.

The remainder (modulus) operator is commonly used in this way. If you start with year 11, $year % 12 will return the remainder of 11 / 12 which is of course 11, so the value is unchanged. However, starting with year 12 the number will wrap back around: The remainder of 12/12 is 0, the remainder of 13/12 is 1 and so on.

As a result, $year % 12 keeps cycling through the numbers 0 through 11 for consecutive years, just as the years cycle through the chinese zodiac.

Upvotes: 3

Related Questions