Fizz Buzz in PHP

Fizz buzz is a fairly common screening question to help sniff out non-programmers during the interview process. The task is to print out numbers 1 through 100 but for multiples of 3 print out “Fizz” instead of the number and for multiples of 5 print “Buzz” instead. If the number happens to be divisble by both 3 and 5 print out “FizzBuzz” instead of the number.

The point of this challenge is to weed out of the most inane people, the ones that really aren’t programmers or if they are, well they don’t have that necessary logic to be good at it. The beauty of the test is that it can be achieved many different ways. Here’s how I solve the problem:

for ($i = 1 $i <= 100 $i++)
{
	$output = ''

	if ($i % 3 == 0)
	{
		$output .= 'Fizz'
	}

	if ($i % 5 == 0)
	{
		$output .= 'Buzz'
	}

	if (!$output)
	{
		$output = $i
	}

	echo $output . "n"
}

I’ve seen the use of foreach (range(1, 100) as $number) and even checking $i % 15 to check for “FizzBuzz” numbers. None of it’s wrong as long as you get the desired output. Got a favorite fizz buzz solution? Post it below!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.