Skip to content

Instantly share code, notes, and snippets.

@nrk
Last active July 16, 2023 16:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrk/7889387 to your computer and use it in GitHub Desktop.
Save nrk/7889387 to your computer and use it in GitHub Desktop.
FizzBuzz'ing in PHP, just for the heck of it.
<?php
// Same approach as of `fizzbuzz_short.php` but with some generators love so you
// can fizzbuzz all you want without blowing up you memory. HOW GREAT IS IT?
$fbrange = function ($start, $stop) {
if ($start > 0) {
for ($n = $start; $n < $stop; $n++) {
yield (($f=!($n%3))|($b=!($n%5)))?($f?'Fizz':'').($b?'Buzz':''):"$n";
}
}
};
foreach ($fbrange(1, 100) as $value) {
echo $value, PHP_EOL;
}
<?php
// This is the shortest form of FizzBuzz in PHP I could think of, using as few
// lines as possible while trying to stay within 80 columns. Readability was not
// the point, so forget about it. Admittedly that bitwise OR is dirty as hell,
// but it suits our purpose. This does not emit any E_NOTICE and neither should
// yours.
echo join(PHP_EOL, array_map(function ($n) {
return (($f=!($n%3))|($b=!($n%5)))?($f?'Fizz':'').($b?'Buzz':''):"$n";
}, range(1, 100)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment