Articles/PHP/FizzBuzz in PHP: A Fresh Approach

FizzBuzz in PHP: A Fresh Approach

FizzBuzz is a very popular programming question that tests your logic to see if you can build a simple program.

November 2, 2018·1 min read

A popular question asked during interviews is to apply the FizzBuzz logic to a range of numbers. This normally means the following:

  1. If a number is divisible by 3, print Fizz.
  2. If a number is divisible by 5, print Buzz.
  3. If a number is divisible by 3 and 5, or 15, print FizzBuzz.

Most examples out there demonstrate solving this problem using traditional loops. I want to try something different though.

Let's solve this using the array_map function.

So let's assume the given range is from 1 to 100.

Instead of writing this: (using loops and a function)

PHP
function translate($number) 
{
    if($number % 15 === 0) {
        return 'FizzBuzz';
    }
    
    if($number % 3 === 0) {
        return 'Fizz';
    }
    
    if($number % 5 === 0) {
        return 'Buzz';
    }
    
    return $number;
}


$results = [];

for($number = 1; $number <= 100; $number++) {
    $results[] = translate($number);
}

We can actually solve it this way below

PHP
$results = array_map(function($number) {
    if($number % 15 === 0) return 'FizzBuzz';
    if($number % 3 === 0) return 'Fizz';
    if($number % 5 === 0) return 'Buzz';
    return $number;
}, range(1,100));

Definitely cleaner to me, and much easier to consume.