PHP Kata: Fizz Buzz for absolute beginners


This article is dedicated to absolute beginners. I will guide you step by step on how to do Fizz Buzz Kata in PHP

Why kata?

Imagine yourself as a piano player. You do scales and passages regularly. Even after you know them all. This is your training. This way your fingers are always ready to play something big - replace something big with your favorite song.

Same thing software developers shall do to practice their kraft. And this is Kata, an exercise you can do to practice or gain new skills.

In this article, I will focus on absolute beginners. So if you never code in PHP or you just code a little - this is something for you. Even if you are a seasoned developer - just do this Kata - but make it state-of-the-art!

Assumptions

For this article, I made few assumptions. I'm obligated to share them with you:

  1. I assume you have basic knowledge about the command console (cmd, bash, or whatever you have on your OS). If no - you can check out my article on [basic Linux commands](https://webee.school/linux/basics/command-line-must-have.html).
  2. I assume you already installed PHP locally on your computer. You can verify it by executing php -v in the command console.

This being said we can start.

No, wait one more thing! I will use GitBash from GitScm for Windows. This is my way of having the Bash on Windows. You can install it also and follow me step by step. If you will use another terminal - please adjust executed commands. E.g. mkdir in Bash -> md on Windows Command Line.

Oh no! Another one thing ;). This was on purpose!

We will implement this Kata in a simple plain PHP (we are in 2021, PHP8 is the only acceptable version ;P). No OOP, frameworks, tests, git, and other things that might distract your focus to what is not important. To be precise - not important right now!

Fizz Buzz

Imagine you are sitting in a classroom. Your math teacher wants to play this funny game. You must repeat a number he said to you. But this can't be so simple. You must follow the below three rules while answering:

  • Rule #1: whenever a number is dividable by 2 - you must say fizz instead of this number;
  • Rule #2: whenever a number is dividable by 3 - you must say buzz instead of this number;
  • Rule #3: whenever a number is dividable by 2 and 3 at the same time - you must say fizzbuzz instead of this number;

Sounds like an easy game? Let's try to code it. And don't worry (be happy) I will guide you through this.

What to begin with?

I will start with opening a terminal window. Now I will try to make you less intimidated by asking you to do two very simple things.

First one - please create an empty directory for our Kata:

mkdir -p ~/webee-school/php-kata/fizz-buzz

The second one - please create a file for the code we will develop:

touch ~/webee-school/php-kata/fizz-buzz/index.php

From PHP perspective you can name this file whatever you want. As long as it will be accepted by your OS. I will stick to index.php without any justification for this decision. Just the first name that I came up with.

Quite simple? I promise I will keep it this way till the end.

Now open index.php in any text editor you like (notepad, vim, nano). I will use vim as it is provided with GitBash by default.

vim ~/webee-school/php-kata/fizz-buzz/index.php

PHP opening tag

We must somehow inform, that the content of our file will be a PHP code. PHP has for this a special tag - opening tag. You must place it at the beginning of the file. To do so type this:

<?php

In vim to start typing, you must switch to appending mode. Do it by pressing a. Now you can type.

Having this in place, PHP will know that everything after this tag must be treated as PHP code. So we can check out if PHP can execute it.

Save changes you made (in vim press following keys: Esc : w). Execute this command in a terminal:

php ~/webee-school/php-kata/fizz-buzz/index.php

You should see nothing - no errors, etc. So nothing is good :)

Congrats! You have your first PHP code developed! It does nothing, but hey it is your first thing that works!

Display something

In PHP there are few ways to display something. We will focus on the simplest one. If you want PHP script to display something you can use echo language construct. Open up our file and edit it, so will look like this:

<?php

echo 'You said 4!';

In PHP every command must be ended with ; - see I added it at the end of the line with echo. We are using apostrophes to indicate that everything between is a text - and should be treated as text. Combining it all - the above script will print out "You said 4!".

Give it try:

php ~/webee-school/php-kata/fizz-buzz/index.php

Your first program just displays something. You have just created so-called Hello World :)

Variables

Do you remember Pythagoras theorem? The one with this formula: a^2 + b^2 = c^2? This formula has a, b, and c in it. Whenever you replace a, b, and c with lengths of the individual sides of the triangle - you can calculate if it is the right triangle. Such placeholders, in software development, are called variables. Variables are used for the generalization of algorithms. Thanks to them you can develop a program that will calculate many triangles. Without them, you would be forced to write a program for each triangle you want to calculate.

When I teach courses, I use such an analogy to explain variables. Imagine variables as boxes. Boxes with different shapes, sizes, and colors. You can put something into the box. You can write on side of it what is inside. You can store this box in a wardrobe. And finally, you can take out whatever you put there.

The same is with variables. You can name variables. Variables are of particular size and type. You can store them if you have enough room. Starting from this moment think about variables as placeholders, boxes for the data your program works with.

To make our script display something that varies. In our particular case - numbers that the teacher asks to repeat. We need a variable - a little box for numbers. In PHP to define a variable, you need to type $ sign followed by a name you like it to have.

$block;
$a;
$veryLongVariableNameWrittenInCammelCaseNotation;

In the above examples you say to PHP: dear, please create for me 3 variables. Notice that, same as for commands - there is ; sign at the end. But usually, we create variables to store something in them. Putting something inside the variable is called an assignment. In PHP to assign value to a variable you need to use equal sign = followed by a value you want to assign. Check out the below examples:

$a = 3;
$b = 4;
$c = 5;
$name = 'Adam';
$country = 'Poland';

Now you can assign a value to a variable. It is time to find out how to use this value:

$number = 7;

echo $number;

The above script will display "7". And as you can see using a variable is as simple as providing its name preceded by $ sign. Having this explained, we will modify our script so it will be able to display number stored in a variable:

<?php

$number = 4;

echo 'You said ' . $number . '!';

Yes, you are right. Now your program will output the same result - but with this slight difference that the number is now taken from the variable. Another thing worth mentioning is a dot . we used. In PHP . is used to concatenate texts. And if you want to extend your professional vocabulary - it is called concatenation operator.

To make our script closer to what we expect from it. We need to figure out how to pass this number into it - as we definitely will not change our code each time number will change.

Script input

PHP is written by clever people. They figure out that we might need to pass something into our script. This is why they prepared a special variable for us. This variable is named $argv. It is special because of few things. The first one, and the most important one is that you don't need to make it. It is already there. It is already defined and provided by PHP. The second thing is that this variable is filled with all the arguments you provided when called a script.

You may ask - what? I didn't fill any arguments. Yes you are right. Look below to find out how to do this:

php /path/to/php/script.php argument1 "Argument number two" 3 "An this one is forth"

In this example, we passed 4 arguments into script.php. Pretty easy, yes? And reading these arguments inside a script is also easy:

<?php

$argument1 = $argv[1];
$argument2 = $argv[2];
$argument3 = $argv[3];
$argument4 = $argv[4];

I'm sure you noticed that again I smuggled something new in this code listing. Look at this $argv variable. After the name and before the semicolon. Yes - number surrounded with square brackets. This is the notation used for variables of an array type. The type of a variable is something like the shape of the box. You need a differently shaped box for your new flat TV and different for your kid's teddy bear. Same is with variables - you need a different type for different data.

Array type indicates nothing more than we are working with a data structure like a table. Yes - such thing as in Excel ;). Please be informed that this is a strong simplification for this tutorial. Each table has cells in it, and those numbers in square brackets are addresses of the cell you want to use. So $argv[1] will represent a value from cell number 1. $argv[2] is for cell number 2, and so on.

We can now use this knowledge to change our script so it will work for any number given on input:

<?php

$number = $argv[1];

echo 'You said ' . $number . '!';

And try it out:

# To return 'You said 5!' execute this:
php ~/webee-school/php-kata/fizz-buzz/index.php 5

# And to return 'You said 17!' execute this:
php ~/webee-school/php-kata/fizz-buzz/index.php 17

I think we are closer to our goal now.

Conditions

You gain a lot of new knowledge. You know:

  • how to start PHP script;
  • how to define a variable;
  • how to assign value to it;
  • how to use a variable;
  • how to display something;
  • how to pass parameters into your script;

This is a lot for few paragraphs so far.

To fulfill requirements defined in the rules. We must be able to define conditions when our script should act differently (fizz and buzz instead of numbers). I think every programming language has the construct for conditions. PHP has it for sure! It is called if statements.

Each if statement is a combination of a condition and instructions to be executed if the condition is met. Condition is enclosed in brackets preceded by the if word and followed by braces containing code to be executed if a condition is true.

if ($number == 7) {
    echo 'The lucky number is 7!';
}

The above code will display the text only if the value in $number variable is equal to 7. Notice that we used two equal signs. This is because the single equal sign is reserved for assigning value to the variable. In PHP there is also a triple equal sign operator - but this is not a story for this article.

Operators

The only thing we missing to finish our code is knowledge about operators. And to be precise I think about one particular operator. And because I just figure it out that today's article is all about math. I'm thinking about modulo - commonly known as rest from division. PHP offer such an operator. It is % sign.

<?php

echo 4 % 3;

echo 10 % 2;

The first statement will display 1 and the second one will display 0. Do you follow me? And can you figure out how this is helpful in our solution?

Check this out - a number is dividable by another number if the rest from the division is equal to zero. So $number % 2 will be 0 only if $number is dividable by 2. Same for 3: $number % 3 will be 0 if $number is dividable by 3. Now we can use this in our script:

<?php

$number = $argv[1];

if ($number % 2 == 0) {
    echo 'fizz';
}

if ($number % 3 == 0) {
    echo 'buzz';
}

echo 'You said ' . $number . '!';

Have you tried it yet? Not exactly what we were looking for! Don't worry - we will fix it. Do you have an idea how?

Test cases

First of all, we need to figure out test data we can work with. I propose numbers: 1, 2, 3, and 6. Why? See this:

  • 1 -> You said 1!
  • 2 -> You said fizz!
  • 3 -> You said buzz!
  • 6 -> You said fizzbuzz!

As you can see, with four numbers we covered all possible results of our script. From this, we know we need to add additional conditions. But before that, we need to fix how we display results. We will introduce a new variable to hold our result. We will name it $result (Hello captain obvious!). Our script might look like this:

<?php

$number = $argv[1];
$result = $number;

if ($number % 2 == 0) {
    $result = 'fizz';
}

if ($number % 3 == 0) {
    $result = 'buzz';
}

echo 'You said ' . $result . '!';

As still not perfect, it is a tiny step to better. Now we need to add the missing condition. But to do so I need to share a secret with you first. In PHP you can type complex conditions. Assume you would like to display cars that are red and blue. For joining condition you can use AND operator. But there are two AND operators in PHP: and and &&. Both do the same, but as simplest as possible && is more important than and. Having this explained we can fix our script like this:

<?php

$number = $argv[1];
$result = $number;

if ($number % 2 == 0) {
    $result = 'fizz';
}

if ($number % 3 == 0) {
    $result = 'buzz';
}

if ($number % 2 == 0 && $number % 3 == 0) {
    $result = 'fizzbuzz';
}

echo 'You said ' . $result . '!';

Congratulations!!! You have a script that prints correct results. Maybe it is not the prettiest, the most accurate, or the most whatever solution - but it is your first script. Remember this moment - you are a software developer!

This is the first of few (or many - if I find it necessary) tutorials on Fizz-Buzz Kata. In the next ones, I will show you how to refactor code, so it will be the state-of-the-art solution. With each refactor you will gain new knowledge about PHP and general coding concepts.

I hope you like this article. If so, please do something for me. Repeat this Kata every 3 days, for as long as you need to do it without looking at code snippets from this article.

That's it. Have a nice coding!

P.S. Checkout next article in the series: [Fizz Buzz Kata in PHP for not so absolute beginners](https://webee.school/coding/php/kata/fizz-buzz-for-not-so-absolute-beginners.html)

Not enough?


Would you like me to build and conduct training tailored to your needs? I'm waiting for your call or message.

address icon

WeBee.Online Adam Wojciechowski
ul. Władysława Łokietka 5/2
70-256 Szczecin, Poland