How to use a while loop in PHP to output a pyramid.
In PHP, nested while loops can be used to output a pyramid shape. Below is an example code:
$height = 5; // 金字塔的高度
$row = 1;
while ($row <= $height) {
// 打印空格
$spaces = $height - $row;
$col = 1;
while ($col <= $spaces) {
echo " ";
$col++;
}
// 打印星号
$stars = 2 * $row - 1;
$col = 1;
while ($col <= $stars) {
echo "*";
$col++;
}
echo PHP_EOL;
$row++;
}
In the code above, we have utilized three while loops. The first while loop controls the number of rows in the pyramid, the second while loop prints the spaces in each row, and the third while loop prints the stars in each row.
The output is:
*
***
*****
*******
*********
You can adjust the height of the pyramid as needed by changing the value of the $height variable.