PHP FizzBuzz Test

Read again about the FizzBuzz test on Joey Devilla’s Global Nerdy blog today and got thinking about the solution. By no stretch of the imagination do I consider my self an amazing programmer, but I thought I should figure out an easy way to do this, should the occasion permit itself to do the test someday.

The basic requirement follows:

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

If any language is kosher, I chose PHP, and this is what I came up with:

$numbers = range( 1, 100 );
foreach ( $numbers as $number ) {
    if ( $number % 15 === 0 ) {
        echo 'FizzBuzz<br />';
    } elseif ( $number % 5 === 0 ) {
        echo 'Buzz<br />';
    } elseif ( $number % 3 === 0 ) {
        echo 'Fizz<br />';
    } else {
	echo $number . '<br />';
    }
}

After thinking about it, and to be a little closer to the requirements, you could rewrite it like this, just using a for loop. I’m filing this away as the theoretical best practice.

for($number = 1; $number <= 100; $number++) {
    if( $number % 3 == 0 && $number % 5 == 0 ) {
        echo 'FizzBuzz';
    } elseif( $number % 5 == 0 ) {
        echo 'Buzz';
    } elseif( $number % 3 == 0 ) {
       echo 'Fizz';
    } else {
        echo $number;
    }
}

8 Comments

  1. Just to one up the previous comment. You could of course write it like this,
    but who would understand it?
    <?while($i++

    There is a deliberate bug in the code, can you fix it?

    The true secret to any algorithm is not to write it as small as possible, but clear enough for your maintenance team to understand and debug!

  2. We could go one better with
    <?while($i++

    However, there is a small bug in the above code. Can you see what it is?

    The secret to writing great algorithms isn’t about writing the least amount of code, but rather about writing easy to understand and debug. You have to consider the maintenance teams that will be fixing your code once you’re gone

Leave a Reply to threenineCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.