Fizz Buzz in PHP

Josh Sherman
1 min read
Software Development PHP Career

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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

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

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles