Skip to content
Advertisement

Fizz Buzz in PHP

I am trying to solve this :

Given the input number, n, return a string containing every value from 1 to n, inclusive. But first, you must follow the rules listed below.

Between each value, add a newline (“n”). Do not have any trailing newline after the last value.

Rules:

For each value, you must follow the following rules:

If the value is a multiple of 3, print the string “Fizz” If the value is a multiple of 5, print the string “Buzz” If the value is a multiple of both 3 & 5, print the string “FizzBuzz” Otherwise, print the integer value

Codes:

function fizz_buzz($n) {
if($n <= 0) 
    echo "Invalid";
else
    if($n%3 == 0 && $n%5 == 0){
        echo 'FizzBuzz';
    }else if($n%3 == 0){
        echo "Fizz";
    }else if($n%5 == 0){
        echo "Buzz";
    }else{
        echo $n;
    }
    echo "n";
}

ERRORS:

estShouldWorkFor1
Log
1
Failed asserting that null is identical to '1'.

 testShouldWorkFor2
 Log
 2
 Failed asserting that null is identical to '1
   2'.

Should fulfill these test :

class FizzBuzzSolution extends TestCase
{
    public function testShouldWorkFor1() {
      $this->assertSame("1", fizz_buzz(1));
    }
    public function testShouldWorkFor2() {
      $this->assertSame("1n2", fizz_buzz(2));
    }
    public function testShouldWorkFor3() {
      $this->assertSame("1n2nFizz", fizz_buzz(3));
    }
    public function testShouldWorkFor5() {
      $this->assertSame("1n2nFizzn4nBuzz", fizz_buzz(5));
    }
}

Advertisement

Answer

You are almost there. You need to loop $n times, to concatenate the strings/numbers together with newline and to return the final string:

<?php
    function fizz_buzz($n){
        if($n <= 0) return false;
        $output = '';
        for($i = 1; $i <= $n; $i++){
            if($i % 3 == 0 && $i % 5 == 0){
                $output .= 'FizzBuzz';
            }else if($i % 3 == 0){
                $output .= "Fizz";
            }else if($i % 5 == 0){
                $output .= "Buzz";
            }else{
                $output .= $i;
            }

            if($i != $n){
                $output .= 'n';
            }
        }

        return $output;
    }

    $str = fizz_buzz(15);
    echo $str;
?>

Output for first 15 numbers (because 15 is the first one you can divide on both 3 and 5):

1n2nFizzn4nBuzznFizzn7n8nFizznBuzzn11nFizzn13n14nFizzBuzz
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement