PHP FizzBuzz solution

FizzBuzz is a math game that is based on division.

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. The phrase “FizzBuzz” is used if a number is divisible by both three and five.

Students and interviewees are often given the task of writing PHP code that replicates the game, as it tests their logic and ability to write a simple application.

The following is an example of the FizzBuzz game being implemented in PHP:


foreach(range(1, 100) as $number){
    //If the number is divisible by 3 and 5, then it is FizzBuzz.
    if($number % 3 == 0 && $number % 5 == 0){
        echo 'FizzBuzz<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, print the number by itself.
    else{
        echo $number, '<br>';
    }
}

In the example above, we are using the % (percentage) sign, which is the 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 operator in action:

$result = 17 % 5;
echo $result; //Answer is 2.

The result is 2 because 17 divided by 5 = 3, with 2 being the remainder.