How to implement php to print out the chessboard, php to print out the chessboard
The examples in this article describe two implementation methods of php printing output chessboard. Share it with everyone for your reference. The specific implementation method is as follows:
Example 1, the code is as follows:
Copy code The code is as follows:
/**
* Change colors in alternate rows and columns
* string fun_table(int $rows=9,int $cols=9)
* $rows represents the number of rows and must be an integer and must be between 1-20
* $cols represents the number of columns and must be an integer and must be between 1-20
*/
function fun_table($rows=9,$cols=9){
if ($rows<1 || $rows>20){
Return "Must be an integer and must be between 1-20";
}
if ($cols<1 || $cols>20){
Return "Must be an integer and must be between 1-20";
}
if($rows!=(int)($rows)){
Return 'The number of rows must be an integer';
}
if($cols!=(int)($cols)){
Return 'The number of columns must be an integer';
}
$str="";
$str.= "
";
for ($i=1;$i<=$rows;$i++){
$str.= "";
for ($j=1;$j<=$cols;$j++){
If(($i+$j)%2){
$str.= "";
}else{
$str.= " | | ";
}
}
$str.= "
";
}
$str.= "
";
return $str;
}
echo fun_table();
?>
Example 2 Simple implementation of chessboard-for loop
To implement this chessboard, first of all, let’s think about what the chessboard looks like. It is composed of many squares, and then it is composed of black and white squares. First, we draw the squares. The code is as follows:
Copy code The code is as follows:
echo "
";
for ($i=1;$i<=10;$i++){
echo "";
; for ($j=1;$j<=10;$j++){ ;
echo "54im | ";
}
echo "
";
}
echo "
";
?>
After seeing the chessboard above, consider the placement of the black and white squares. There is a rule and you can find that the white squares in the horizontal and vertical rows are all cardinal numbers, and the black squares are all even numbers. We can use the remainder method to determine which square should be displayed. What color? I want the base cells to display white, and the even cells to display black. Base number + even number = even number, so we can easily find the even cells (black), and the rest is the base cell (white). The code is as follows:
Copy code The code is as follows:
/**
Implementing chessboard through for loop and html
**/
echo "
";
for ($i=1;$i<=10;$i++){
echo "";
; for ($j=1;$j<=10;$j++){ ;
If(($i+$j)%2){
echo "";
}else{
echo " | | ";
}
echo "
";
}
echo "
";
?>
I hope this article will be helpful to everyone’s PHP programming design.
http://www.bkjia.com/PHPjc/932072.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/932072.htmlTechArticleHow to implement php printout chessboard, php printout chessboard This article describes two implementations of php printout chessboard method. Share it with everyone for your reference. The specific implementation method is as follows...