Chessboard with PHP, HTML and CSS






In this small code, I’ll teach you how to create a chessboard in a simple way with PHP, HTML and CSS. Just have to make a table with a loop in php and apply styles.

chessborad php

See live example clicking here.
Code index.php (without form)


<html>
<head>
<title>Chessboard with PHP, HTML and CSS - Ajax101.com</title>
<style>
table{
border: solid 1px;
}
table tr td{
width: 50px;
height: 50px;
}
.black {
background-color: #000000;
}
</style>
</head>

<?php
echo "<table>";
for ($i=0; $i < 8; $i++) {
echo "<tr>";
for ($j=0; $j < 8; $j++) {
?>
<td class="<?php echo (!($i %2)xor($j%2))?'white':'black';?>" >&nbsp;</td>
<?php
}
echo "</tr>";
}
echo "</table>";
?>

</html>

Now, if you want to define the number of rows and columns using a form (as seen in the example), you can use this code:
Code index.php (with form)


 

<html>
<head>
<title>Chessboard with PHP, HTML and CSS - Ajax101.com</title>
<style>
table{
border: solid 1px;
}
table tr td{
width: 50px;
height: 50px;
}
.black {
background-color: #000000;
}
</style>
</head>

<?php
$rows=$_POST['rowsValue'];
$columns=$_POST['columnsValue'];

if (!isset($rows)){
$rows=8;
$columns=8;

}

echo "<table>";
for ($i=0; $i < $rows; $i++) {
echo "<tr>";
for ($j=0; $j < $columns; $j++) {
?>
<td class="<?php echo (!($i %2)xor($j%2))?'white':'black';?>" >&nbsp;</td>
<?php
}
echo "</tr>";
}
echo "</table>";
?>

<form action="index.php" method="POST">
Rows: <input type="text" name="rowsValue"/><br/>
Columns <input type="text" name="columnsValue"/><br/>
<input type="submit" value="Create new chessboard"/>
</form>
</html>




 
Leave a Comment
Your comment: