A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break within either the inner or outer loop would interrupt this process.
You may also like: PHP Nested for loop Examples
Code: Write a PHP script using nested for loop that creates a chess board
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Code4Example</title> <style> table{ border:10px double red; padding:10px; border-spacing:1px; } table td{ width:50px; height:50px; border:1px solid red; } td.black{ background:#000; } td.white{ background:#eee; } </style> </head> <body> <?php echo "<table>"; for($row=1;$row<=8;$row++) { echo "<tr>"; for($column=1;$column<=8;$column++) { $total=$row+$column; if($total%2==0) { echo "<td class='black'></td>"; } else { echo "<td class='white'></td>"; } } echo "</tr>"; } echo "</table>"; ?> </body> </html> |
Output: