Write a program to create Chess board in PHP using for loop

Description: Write a PHP program that creates a chess board using nested for loops.

Rules and hints:

  • Use an HTML table. Make each square 50px wide and 50px high.
  • The squares must be black and white, one after the other.
  • Hint: if the sum of the row number and the column number is even, use white, otherwise black.

PHP program to create a chess board

<?php
echo '<table border="1" cellspacing="0" cellpadding="0">';

for ($row = 1; $row <= 8; $row++) {
    echo "<tr>";

    for ($col = 1; $col <= 8; $col++) {
        $color = (($row + $col) % 2 == 0) ? "white" : "black";
        echo '<td style="width:50px;height:50px;background:' . $color . '"></td>';
    }

    echo "</tr>";
}

echo "</table>";
?>

Output:

Tutorials Class - Output Window

An 8 x 8 table of black and white squares, like a chess board

How it works

  • The outer loop creates the 8 rows (<tr>), and the inner loop creates 8 cells (<td>) in every row.
  • ($row + $col) % 2 is 0 for every second square, so the colors change like on a real chess board.
  • The ternary operator picks the color. See PHP Ternary Operator.

Learn more about the similar topics:
Tutorials
PHP Loops
Exercises & Assignments
Write a program to count 5 to 15 using PHP loop
Write a factorial program using for loop in php
Factorial program in PHP using recursive function
Write a program to create Chess board in PHP using for loop
Write a Program to create given pattern with * using for loop
Interview Questions & Answers
No Content Found.