Fizz Buzz is a math game that is based on division. To sum it up: Participants count up from the number one, saying “Fizz” when the number is divisible by three and “Buzz” when the number is divisible by five. If a number happens to be divisible by both three and five, then the phrase “Fizz Buzz” is used (the number 15 is a good example).
In the programming world, students and interviewees are often given the task of writing a piece of software that replicates the logic of the game.
Here is an example of the Fizz Buzz game being implemented in PHP:
<?php //A foreach loop that goes between 1 and 100. foreach(range(1, 100) as $number){ //Use the Modulus arithmetic operator. //If the number is divisible by both 3 and 5, then it is Fizz Buzz. if($number % 3 == 0 && $number % 5 == 0){ echo 'Fizz Buzz', '<br>'; } //If the number is divisible by 3, then it is Fizz. elseif($number % 3 == 0){ echo 'Fizz', '<br>'; } //If the number is divisible by 5, then it is Buzz. elseif($number % 5 == 0){ echo 'Buzz', '<br>'; } //If it isn't divisible by 3 or 5, just print out the number. else{ echo $number, '<br>'; } }
As you can see, we made use of the % percentage sign, which is Modulus arithmetic operator in PHP. This operator will return the remainder of a given division sum. The number to the right of the modulus percentage sign is divided into the number on the left.
An example of PHP’s Modulus arithmetic operator in action:
<?php $result = 17 % 5; echo $result; //Answer is 2.
The result is 2 because 17 divided by 5 = 3, with 2 being the remainder.