How to produce a chessboard pattern in PHP
In this lesson we will create a chessboard pattern, an 8x8 grid of black and white squares like this:
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:
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:
We now need to consider how we will colour the squares.
First of all, let's consider a numbered chessboard like this:
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.
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.