Create a Chess board in PHP
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'>
<?php
for($i=1; $i<9;$i++)
{
?> <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
}
else
{
?> <td width = 80px; height = 80px;> </td><?php
}
}
?> </tr> <?php
}
?>
</table>
So this way we can create a chessboard in PHP. If you have any query then please leave your comments.
Comments (0)
Leave a comment
Related Blogs
Introduction to Kibana
Aug 1, 2020, 6:19:45 PM | Anurag Srivastava
Bucket Aggregation in Elasticsearch
Aug 29, 2018, 7:15:06 PM | Anurag Srivastava
Metrics Aggregations in Elasticsearch
Aug 18, 2018, 6:02:20 PM | Anurag Srivastava
Introduction to Elasticsearch Aggregations
Aug 14, 2018, 4:47:56 PM | Anurag Srivastava
Wildcard and Boolean Search in Elasticsearch
Aug 10, 2018, 7:14:40 PM | Anurag Srivastava
Basics of Data Search in Elasticsearch
Aug 4, 2018, 7:02:21 AM | Anurag Srivastava
Top Blogs
Wildcard and Boolean Search in Elasticsearch
Aug 10, 2018, 7:14:40 PM | Anurag Srivastava
Elasticsearch REST APIs
Jul 31, 2018, 6:16:42 PM | Anurag Srivastava
How to count number of words in a HTML string and find Read time in Python 3
Jun 30, 2018, 12:07:47 PM | jitender yadav
Create a Chess board in PHP
Mar 9, 2020, 8:45:41 AM | Rocky Paul
Bucket Aggregation in Elasticsearch
Aug 29, 2018, 7:15:06 PM | Anurag Srivastava
Metrics Aggregations in Elasticsearch
Aug 18, 2018, 6:02:20 PM | Anurag Srivastava