Home > Backend Development > PHP Tutorial > PHP implements while loop to print solid diamond

PHP implements while loop to print solid diamond

WBOY
Release: 2024-03-16 09:22:02
Original
878 people have browsed it

PHP implements while loop to print solid diamond

PHP implements while loop to print solid diamonds

In PHP, we can achieve the effect of printing solid diamonds through nested while loops . The following is a specific code example:

<?php
//Set the size of the diamond
$size = 5;

//Print the upper part of the diamond
$row = 1;
while ($row <= $size) {
    $col = 1;
    while ($col <= $size - $row) {
        echo " ";
        $col;
    }
    $col = 1;
    while ($col <= 2 * $row - 1) {
        echo "*";
        $col;
    }
    echo "
";
    $row ;
}

//Print the lower half of the diamond
$row = $size - 1;
while ($row >= 1) {
    $col = 1;
    while ($col <= $size - $row) {
        echo " ";
        $col;
    }
    $col = 1;
    while ($col <= 2 * $row - 1) {
        echo "*";
        $col;
    }
    echo "
";
    $row--;
}
?>
Copy after login

In the above code, we first set the size of the diamond to 5, and then print out the solid diamond through the nested while loop. The printing logic of the upper and lower halves is slightly different, but both achieve the diamond shape by controlling the number of spaces and asterisks.

I hope the above code is helpful to you. If you have any questions or need further explanation, please feel free to contact me.

The above is the detailed content of PHP implements while loop to print 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