The Modulus operator, The Ternary operator and FizzBuzz in PHP

 

 

Happy new year! I’ve disabled my Facebook so I think I will start writing here more often..

Anyway, I wanted to talk about the Modulus operator % in PHP (which is very similar to most other programming languages).

From the PHP docs, we know that it returns the “Remainder of $a divided by $b“. But what does that mean?

It means that it will return the difference between $a and the first number which can be cleanly divided by $b if you start counting down from $a.

Here are a few examples

(3 % 3) = 0 (0 because 3 itself can be  divided by 3 cleanly)
(4 % 3) = 1 (1 because if we start counting down, 3 is the first number that can be divided by 3 which leaves us a reminer of 1)
(5 % 3) = 2
(6 % 3) = 0
(7 % 3) = 1
(8 % 3) = 2
(9 % 3) = 0

To create your own examples like above, you could use this loop code:
<?php
for ($i=1; $i<100; $i++)
{
$res = ($i % 3);
echo "<br />({$i} % 3) = {$res}";
}
?>

Usage examples

Here is an example where we calculate how many apples we can buy and what change will be left:
<?php
//the money we have:
$myMoney = 134;

//the price of an apple:
$applePrice = 3;

//the change which will be left after we buy all the apples:
$change = ( $myMoney % $applePrice);

//the cost of the apples:
$applesCost = ( $myMoney - $change );

//the number of apples we can buy:
$apples = $applesCost / $applePrice;

echo "We have &pound;{$myMoney} which will be enough to buy {$apples} apples if the price of an apple is &pound;{$applePrice}. The total cost will be &pound;{$applesCost} that means we will have &pound;{$change} change left.";

?>

The above example will result in:
We have £134 which will be enough to buy 44 apples if the price of an apple is £3. The total cost will be £132 that means we will have £2 change left.

Highlighting every second row
The most common usage of the modulus operator I have seen so far in PHP is identifying every n-th element (every second element, every third element, etc).
As you have noticed from the examples above, the reminder is 0, if a number can cleanly be divided.

So here is an example of how we can highlight every second result
<?php
for ($i=1;$i<100;$i++)
{
echo '<span';
if ( !($i % 2) ) { echo ' style="color: red;"'; }
echo '>' . $i . '</span>';
}
?>

The above will output:
123456789
Pay attention to the IF statement line “if ( !($i % 2) ) “. Basically we are saying “if $i % 2 returns false, then echo the inline style which adds the red colour CSS property”. As you might have seen above, the operator does not return bool (true or false) values but it returns integers. However, PHP is a loose-type language and it converts zeros to False and all other numbers to True if it finds a context where an integer has to be used as bool.
For that reason, there is nothing wrong with the IF line, however if we want to reduce the work that PHP has to do by eliminating the conversion, we could compare it vs 0 by saying “if ( ($i % 2) == 0 ) “, which does exactly the same but is better because there are no conversions in place and the expression is valid bool. An even better example will be “if ( ($i % 2) === 0 ) ” which again does the same comparison but it is also checking if both numbers are of the integer data type.

Now, since all that we are doing is ECHO, we could also use the ternary operator (?) (also known as a conditional operator) which you will find is very popular for cases like this:
<?php
for ($i=1;$i<100;$i++)
{
echo '<span';
echo ( ($i % 2) == 0 ) ? ' style="color: red;"' : '';
echo '>' . $i . '</span>';
}
?>

The ? operator does exactly the same as the IF statement in the previous example.

If you prefer one-liners, here is how you could do the same echo:
<?php
for ($i=1;$i<100;$i++)
{
echo '<span' . ( ( ($i % 2) == 0 ) ? ' style="color: red;"' : '' ) . '>' . $i . '</span>';
}
?>

So all we did there was wrap the ternary expression in brackets () and embed it within the string we are echo-ing.

FizzBuzz exercise

One of most popular job interview tasks is the FizzBuzz classic which makes good use of the modulus operator:

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

If you go for a job interview, it is likely that you will be asked to do this. If you have understood everything I have said in this article so far and you have basic PHP experience, you will not have any problems of doing this on your own.

Here is my example:

<?php
for ($i=1;$i<=100;$i++)
{
if ( ($i % 3) === 0) { echo 'Fizz'; }
if (($i % 5) === 0) { echo 'Buzz'; }
if ( ( ( $i % 5 ) != 0 ) && ( ($i % 3) != 0 ) ) { echo $i; }
echo '<br />';
}
?>

And here is the same example with ternary operators:

<?php
for ($i=1;$i<=100;$i++)
{
echo ( ($i % 3) === 0) ? 'Fizz' : '';
echo (($i % 5) === 0) ? 'Buzz' : '';
echo ( ( ( $i % 5 ) != 0 ) && ( ($i % 3) != 0 ) ) ? $i : '';
echo '<br />';
}

We could also unite the ternary expressions (with brackets like in the above example). Here is the first two echo-es united:

<?php
for ($i=1;$i<=100;$i++)
{
echo ( ( ($i % 3) === 0) ? 'Fizz' : '' ) . ( (($i % 5) === 0) ? 'Buzz' : '' );
echo ( ( ( $i % 5 ) != 0 ) && ( ($i % 3) != 0 ) ) ? $i : '';
echo '<br />';
}
?>

And here is all the echo-es united into one:


<?php
for ($i=1;$i<=100;$i++)
{
echo ( ( ( ( $i % 5 ) != 0 ) && ( ($i % 3) != 0 ) ) ? $i : ( ( ( ($i % 3) === 0) ? 'Fizz' : '' ) . ( (($i % 5) === 0) ? 'Buzz' : '' ) ) ) . '<br />';
}
?>

Yes, it’s possible to unite all the echo-es into one, but I wouldn’t reccomend it for the simple reason that it will make a programmer cry blood if they have to read it and follow it.
In my opinion, the example with the four echo-es is the best becasue it is easy to follow.

Well, that’s all i could think of about the Modulus operator – it’s bed time for me 🙂