Skip to content

Instantly share code, notes, and snippets.

@rattfieldnz
Forked from veb/fizzbuzz2.php
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattfieldnz/5737d1e7cca1713b44d9 to your computer and use it in GitHub Desktop.
Save rattfieldnz/5737d1e7cca1713b44d9 to your computer and use it in GitHub Desktop.
<?php
/*
* 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".
*
* Instructions:
* This file (fizzbuzz.php) can be uploaded to a webserver that's running PHP4+ and executed with "php fizzbuzz.php" from the command line.
* Alternatively, this file can be accessed directly (if webserver permissions allow) via your browser.
*
* Author: Mike Mackenzie <mike@veb.co.nz>
*/
for ($i = 1; $i <= 100; $i++)
{
/*
* Using modular arithmetic we can easily compare the given conditions with the integer in the loop to determine the modulus.
* The conditions are 3, 5 and 15. We can use 15 (instead of two big conditional statements) as the aforementioned 3 and 5 are two
* distinct prime factors of 15.
*
* This implementation is slower, and over engineered, but I wrote it on the principle that you should be able to add more conditions.
* I wanted to keep the code small, and following the DRY principle. I know that this is only limited to if you want to add more modulus
* conditions, or change the text returned. Not a good implementation for production.
*/
$cond['Fizz'] = 3;
$cond['Buzz'] = 5;
$x = $i;
foreach($cond as $k => $v) {
if ($i % $v == 0) {
echo $k;
$x = null;
}
}
echo "$x <br/>\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment