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.
Leave a comment
Dec 24, 2018, 5:25:28 PM | Anurag Srivastava
Aug 14, 2018, 4:47:56 PM | Anurag Srivastava
Aug 29, 2018, 7:15:06 PM | Anurag Srivastava
Aug 4, 2018, 7:02:21 AM | Anurag Srivastava
Aug 18, 2018, 6:02:20 PM | Anurag Srivastava
Feb 2, 2018, 7:29:35 PM | jitender yadav
Dec 30, 2019, 11:20:08 AM | Anurag Srivastava
Dec 31, 2019, 1:33:53 PM | Anurag Srivastava
Jun 21, 2018, 4:58:11 AM | Anurag Srivastava
Jun 26, 2018, 4:50:18 PM | Anurag Srivastava
Jul 16, 2018, 5:00:02 PM | Anurag Srivastava
Jun 13, 2018, 3:44:01 PM | Anurag Srivastava
May 12, 2018, 4:47:07 PM | Anurag Srivastava
Mar 9, 2019, 8:20:38 AM | Anurag Srivastava
Apr 24, 2018, 2:52:28 PM | Anurag Srivastava
Jun 2, 2018, 10:49:54 AM | Anurag Srivastava