How can I output a diamond pattern in PHP?

Here is an example of printing a diamond pattern using PHP code:

<?php

function printDiamond($n) {
    for ($i = 1; $i <= $n; $i++) {
        for ($j = 1; $j <= $n - $i; $j++) {
            echo " ";
        }

        for ($j = 1; $j <= 2 * $i - 1; $j++) {
            echo "*";
        }

        echo "\n";
    }

    for ($i = $n - 1; $i >= 1; $i--) {
        for ($j = 1; $j <= $n - $i; $j++) {
            echo " ";
        }

        for ($j = 1; $j <= 2 * $i - 1; $j++) {
            echo "*";
        }

        echo "\n";
    }
}

$n = 5;
printDiamond($n);

In the example above, the printDiamond function is used to print a diamond pattern, with the $n variable specifying the size of the diamond. You can adjust the size of the diamond by changing the value of $n. Running the above code will print a diamond pattern in the command line.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds