In this blog, I am going to show you how to create a chessboard in PHP. In a chessboard, we have 8 rows and 8 columns with black and white boxes. The history of chess is around 1500 years old. So as we have to draw 64 boxes (8 rows and 8 columns) let us plan how we should proceed.
- We should run two loops to create the 64 boxes.
- The outer loop should run 8 times.
- The inner loop should also run 8 times. So for each outer loop iteration, the inner loop will run 8 times.
Now comes the question, how to plot a table using this loop. So the answer is to create the '<table>' tag before the loop. Put the '<tr>' tag outside the inner loop and put the '<td>' tag inside the inner loop as this will actually draw the boxes.
We should also put the table border so that we can actually see the boxes on the web page. After this, we would be able to generate 64 boxes. Now we should add the condition to change the background colors of the alternate boxes to black and white. This can be achieved by adding the counter of the inner and outer loop and take the modules to apply the background logic.
The last thing is to set the height and width of the boxes so that they can look like the below screenshot:
The above screenshot is showing the output of the PHP program. Please refer to the below PHP program where we have put the complete logic which was used to generate the above chessboard.
<table border = '2'>
?> <tr> <?php
for($j=1; $j<9; $j++)
$total = $i+$j;
if($total%2 == 0)
?> <td style="background-color: black;" width = 80px; height = 80px;> </td><?php
?> <td width = 80px; height = 80px;> </td><?php
?> </tr> <?php
So this way we can create a chessboard in PHP. If you have any query then please leave your comments.
You may like to read
Leave a comment
Jun 27, 2021, 12:50:31 PM | Anurag Srivastava
Nov 29, 2020, 5:16:40 PM | Anurag Srivastava
Sep 12, 2020, 3:58:55 PM | Anurag Srivastava
Aug 1, 2020, 6:19:45 PM | Anurag Srivastava
Dec 31, 2019, 1:33:53 PM | Anurag Srivastava
Dec 30, 2019, 11:20:08 AM | Anurag Srivastava
Aug 10, 2018, 7:14:40 PM | Anurag Srivastava
Jul 31, 2018, 6:16:42 PM | Anurag Srivastava
Jun 30, 2018, 12:07:47 PM | jitender yadav