The Fizz Buzz

FizzBuzz is a very simple programming task, used in software developer job interviews, to determine whether the job candidate can actually write code.  It was invented by Imran Ghory, and popularized by Jeff Atwood. Here is a description of the task:

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

Since I write in PHP most days, my solution to this simple puzzle is below.  This code took me about six minutes from start to finish when asked to create it off-the-cuff.


echo '<pre>'; // just to make it human readable

for ($i = 1; $i <= 100; $i++) {

    // is it a multiple of 3?
    $f = $i % 3 ? '' : 'fizz';

    // is it a multiple of 5?
    $b = $i % 5 ? '' : 'buzz';

    // if the concatenation yields anything, 
    // show the concatenated value otherwise, 
    // just show the iterator
    echo $f . $b ? $f . $b : $i;

    // a delimiter wasn't specified, so I chose new 
    // line to make human readable
    echo PHP_EOL;


To see my code run,  click here.

Enjoy.  And yes, Virginia, I can write code.   😉