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;
    }
}