hello how can i print a chess table in PHP without using for loops, is it possible to do it with conditional and logical statements only?
<table width = "270px" cellspacing = "0px" cellpadding = "0px" border = "1px" bordercolor = "gray">
<?php
$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>";
}
?>
CodePudding user response:
You could use str_repeat
:
<table width="270px" cellspacing="0" cellpadding="0" border="1px" bordercolor="gray">
<?php
$td = '<td height="40px" width="20px" bgcolor=';
$black = "$td'black'></td>";
$white = "$td'white'></td>";
echo str_repeat("<tr>" . str_repeat($black . $white, 4) . "</tr><tr>"
. str_repeat($white . $black, 4) . "</tr>", 4);
?>
</table>
CodePudding user response:
One solution is to use build-in loops
derived from some functions, here array_walk
(only to avoid explicit for
).But it the end the algorithm is the same. It's only a trick !
<?php
$arr = array_fill(0,64,1);
array_walk($arr,"construct");
array_walk($arr,"display");
function construct(&$item, $key)
{
$color=$key%2;
$i=($key-$key%8)/8 1;
if($i%2==0)
$color = ($color 1)%2;
$color = $color%2==0 ? "white" : "black";
$j=$key%8 1;
$item = new Square($i,$j,$color);
}
function display($item, $key)
{
if($key%8==0) echo "<br>";
echo $item." ";
}
class Square
{
public $i;
public $j;
public $color;
public function __construct($i,$j,$color)
{
$this->i=$i;
$this->j=$j;
$this->color=$color;
}
public function __toString()
{
return "[".$this->i.",".$this->j."]=".($this->color);
}
}
?>
Output:
[1,1]=white [1,2]=black [1,3]=white [1,4]=black [1,5]=white [1,6]=black [1,7]=white [1,8]=black
[2,1]=black [2,2]=white [2,3]=black [2,4]=white [2,5]=black [2,6]=white [2,7]=black [2,8]=white
[3,1]=white [3,2]=black [3,3]=white [3,4]=black [3,5]=white [3,6]=black [3,7]=white [3,8]=black
[4,1]=black [4,2]=white [4,3]=black [4,4]=white [4,5]=black [4,6]=white [4,7]=black [4,8]=white
[5,1]=white [5,2]=black [5,3]=white [5,4]=black [5,5]=white [5,6]=black [5,7]=white [5,8]=black
[6,1]=black [6,2]=white [6,3]=black [6,4]=white [6,5]=black [6,6]=white [6,7]=black [6,8]=white
[7,1]=white [7,2]=black [7,3]=white [7,4]=black [7,5]=white [7,6]=black [7,7]=white [7,8]=black
[8,1]=black [8,2]=white [8,3]=black [8,4]=white [8,5]=black [8,6]=white [8,7]=black [8,8]=white
For html grid, just adapt display
.
function displayHtml($item, $key)
{
if($item->i==1 && $item->j==1)
echo '<table width="270px" cellspacing="0" cellpadding="0" border="1px" bordercolor="gray">';
if($item->j%8==1)
echo "<tr>";
echo "<td height=40px width=20px style='background-color:".$item->color."'></td>";
if($item->j%8==0)
echo "</tr>";
if($item->i==8 && $item->j==8)
echo "</table>";
}