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 *

About Christina M. Gleason

Christina GleasonDeveloper who has been playing with websites since I was a preteen, it started with some tables and CSS creating a website about fairies (true story). Since then, I got a BS in Computer Science, and went to work on PHP-based websites and applications. I spent some time in custom frameworks, then a lot of time in custom WordPress development and Magento e-commerce. Industries I've worked in include logistics, healthcare, retirement communities, legal, spiritual, and HVAC.

I am an active knitter, and I also really enjoy scrapbooking and painting. Creativity has always been at my core, and I bring that into my daily workflow all the time. Lifting and working out is also important to me. I'm also married, have two daughters, and two rescue dogs Barlow and Sunshine.

Find me on: Ravelry | Instagram | Twitter | LinkedIn | GitHub