Home >Backend Development >PHP Tutorial >Use PHP to write a while loop to generate a solid diamond
Title: Write a while loop in PHP to generate a solid diamond
In PHP, we can use a while loop to generate a solid diamond. The following uses a specific code example to demonstrate how to use PHP to write a while loop to generate a solid diamond.
<?php // Define the number of rows of the diamond $rows = 7; // the top half for ($i = 1; $i <= $rows; $i ) { //Print spaces on each line for ($j = 1; $j <= $rows - $i; $j ) { echo " "; } //Print each line* $j = 1; while ($j <= 2 * $i - 1) { echo "*"; $j; } echo " "; } // the second half for ($i = $rows - 1; $i >= 1; $i--) { //Print spaces on each line for ($j = 1; $j <= $rows - $i; $j ) { echo " "; } //Print each line* $j = 1; while ($j <= 2 * $i - 1) { echo "*"; $j; } echo " "; } ?>
In the above code, we first defined the number of rows of the diamond as 7 rows. Then it is divided into the upper half and the lower half, and two for loops are used to control the number of rows. In each line, use a while loop to print spaces and *, thereby generating the effect of a solid diamond.
Through the above code example, we can see how to use PHP to write a while loop to generate a solid diamond. Hope this example helps you!
The above is the detailed content of Use PHP to write a while loop to generate a solid diamond. For more information, please follow other related articles on the PHP Chinese website!