Write a program to design a chess board using PHP
Chess is a recreational and competitive board game played between two players. It is played on a square chessboard with 64 squares arranged in an eight-by-eight grid black-white alternatively. In this article, we will learn how to design a Chess Board using PHP.
Approach:
- To create Chess in php; we have to run 2 loops each will create 8 blocks.
- The inner-loop will generate table-row with black/white background-color based upon a value .
- If value is even, Black background is generated .
- If value is odd, White background is generated
Chess Board using For-Loop:
PHP
<!DOCTYPE html>
<html>
<body>
<table width= "400px" border= "1px" cellspacing= "0px" >
<?php
echo "Chess by GeeksforGeeks" ;
$value = 0;
for ( $col = 0; $col < 8; $col ++) {
echo "<tr>" ;
$value = $col ;
for ( $row = 0; $row < 8; $row ++) {
if ( $value %2 == 0) {
echo
"<td height=40px width=20px bgcolor=black></td>" ;
$value ++;
}
else {
echo
"<td height=40px width=20px bgcolor=white></td>" ;
$value ++;
}
}
echo "</tr>" ;
}
?>
</table>
</body>
</html>
|
Chess Board using while-Loop:
PHP
<!DOCTYPE html>
<html>
<body>
<table width= "400px" border= "1px" cellspacing= "0px" >
<?php
echo "Chess by GeeksforGeeks" ;
$value = 0;
$col = 0;
while ( $col < 8) {
$row = 0;
echo "<tr>" ;
$value = $col ;
while ( $row < 8) {
if ( $value %2 == 0) {
echo
"<td height=40px width=20px bgcolor=black></td>" ;
$value ++;
}
else {
echo
"<td height=40px width=20px bgcolor=white></td>" ;
$value ++;
}
$row ++;
}
echo "</tr>" ;
$col ++;
}
?>
</table>
</body>
</html>
|
Chess Board using do-while loop:
PHP
<!DOCTYPE html>
<html>
<body>
<table width= "400px" border= "1px" cellspacing= "0px" >
<?php
echo "Chess by GeeksforGeeks" ;
$value = 0;
$col = 0;
do {
$row = 0;
echo "<tr>" ;
$value = $col ;
do {
if ( $value %2 == 0) {
echo
"<td height=40px width=20px bgcolor=black></td>" ;
$value ++;
}
else {
echo
"<td height=40px width=20px bgcolor=white></td>" ;
$value ++;
}
$row ++;
} while ( $row < 8);
echo "</tr>" ;
$col ++;
} while ( $col < 8);
?>
</table>
</body>
</html>
|
Output: All the code will give the same output.
Last Updated :
05 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...