Blog Detail

Covid-19 Tracker Ask Question

preview image Programming
by Rocky Paul, Mar 9, 2020, 8:45:41 AM | 2 minutes |

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'>
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
            ?> <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.

Comments (0)

Leave a comment

Related Blogs

Create Sequence Diagrams using PlantUML

Jun 27, 2021, 12:50:31 PM | Anurag Srivastava

Improving your productivity on Linux Terminal

Nov 29, 2020, 5:16:40 PM | Anurag Srivastava

Elastic Stack Interview Questions

Sep 12, 2020, 3:58:55 PM | 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

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