Home > Backend Development > PHP Tutorial > Use PHP to write a while loop to generate a solid diamond

Use PHP to write a while loop to generate a solid diamond

WBOY
Release: 2024-03-15 13:16:01
Original
1251 people have browsed it

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 "
";
}
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template