Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2018 by Frank Perez.

FizzBuzz in PHP - A Fresh Approach

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)

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

$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. Let me know what you think in the comments below.