(919) 964-9842
(919) 964-9842

FizzBuzz in PHP

If you have taken any entrance code exam for employment, you know about the FizzBuzz problem. There are plenty of different ways to do it, so I'm going to show a couple options here.

The problem is:

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".

The most obvious solution is looping through a set of if else statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// using nested if statements
for($i = 0; $i <= 100; $i++){
    if($i % 3 == 0 && $i % 5 == 0) {
        echo "FizzBuzz<br>";
    } else if($i % 3 == 0) {
        echo "Fizz<br>";
    } else if($i % 5 == 0) {
        echo "Buzz<br>";
    } else {
        echo $i . "<br>";
    }
}
?>

We could make it a little more complicated using a switch statement instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// using switch statement
for($i = 0; $i <= 100; $i++){
    switch($i) {
        case $i % 3 == 0 && $i % 5 == 0:
        echo "FizzBuzz<br>";
        break;
        case $i % 3 == 0:
        echo "Fizz<br>";
        break;
        case $i % 5 == 0:
        echo "Buzz<br>";
        break;
        default:
        echo $i . "<br>";
    }
}
?>

What other ways have you solved the FizzBuzz problem?

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *