How to produce a chessboard pattern in PHP

 
chess.png

In this lesson we will create a chessboard pattern, an 8x8 grid of black and white squares like this:

chessboard.png

The chessboard pattern is basically a HTML table consisting of 8 rows each with 8 cells. This is a repeating pattern so we could use a for loop to create a row of the 8 cells and then repeat this within another loop 8 times. In effect, we need a nested loop.

Before we begin coding the loops let us just consider the format of a simple HTML table. To keep the code fairly short I will just show the code for a 2 x 2 table.

We can see that we have repeated lines consisting of a table row and table cells (the td elements).

Now let's add a single loop to produce a row with 8 cells.

Let's add some styling to the row so that we can see it. The default styling for tables in some browsers means that the table cells are not visible by default.

We will set the height and width of the cells and add a border to each cell so that we can see them. Note that we will be changing this later!

We now have a table with one row like this:

Screen Shot 2019-06-25 at 3.09.54 pm.png

This pattern of 8 cells needs to be repeated for each of the 8 rows in the chessboard.

So, we add another loop and nest the first loop inside it as follows:

We now have the following:

Screen Shot 2019-06-25 at 3.11.47 pm.png

We now need to consider how we will colour the squares.

First of all, let's consider a numbered chessboard like this:

Screen Shot 2019-06-25 at 3.12.47 pm.png

The numbers are simply the addition of the row and column numbers.

E.g. the first cell is the first row and the first column so 1 + 1 = 2

Similarly, the cell in the third row and fifth column is a result of adding 3 and 5 to get 8.

If you notice, any cells with an even number need to be coloured black.

We use a conditional statement to assign a class of 'black' to any cell which is an even number. We test for an even number by adding the $row and $column values and then using the modulus operator as follows:

Line 6: we first add the $row and $column. We then check the remainder of this total when it is divided by 2. If the total is an even number then we should get zero when we divide by 2. If we get zero then we render a black square.

We can now adjust our css rules as follows:

We now have the required chessboard pattern.

chessboard.png

If you enjoyed this challenge then you will absolutely love the course it belongs to. You will take what you have learnt above and extend the scripts even further. Every line of code is explained in detail.