在 PHP 中打印没有嵌套循环的图案

Printing a pattern without a nested loop in PHP

我的代码的输出应该是:

*
**
***
****
*****

我目前正在使用带有嵌套 for 循环的代码来获取结果。

for($lineNumber=1;$lineNumber<=5;$lineNumber++) {
    for($starCount=1;$starCount<=$lineNumber;$starCount++)         {
            echo("*");
    }
        echo("<br />");
}

我需要能够在没有嵌套 for 循环的情况下获得相同的结果,但我很难过。我唯一想使用的是一个 for 循环。没有其他的。没有 ifs、开关或其他循环。

谢谢!

$str = '';
for($lineNumber=1;$lineNumber<=5;$lineNumber++) {
    $str = $str . '*';
    echo $str;
    echo("<br />");
}

使用这个字符串累加器就不需要第二个循环了。

使用这个:

for($lineNumber=1;$lineNumber<=5;$lineNumber++) {
    echo str_repeat("*",$lineNumber);
    echo("<br />");
}

这些是绘制金字塔的一些示例:

function print($n)
{
    //example 1
    for ($x = 1; $x <= $n; $x++) {
        for ($y = 1; $y <= $x; $y++) {
            echo 'x';
        }
        echo "\n";
    }

    // example 2
    for ($x = 1; $x <= $n; $x++) {
        for ($y = $n; $y >= $x; $y--) {
            echo 'x';
        }
        echo "\n";
    }

    // example 3

    for($x = 0; $x < $n; $x++) {
        for($y = 0; $y < $n - $x; $y++) {
            echo ' ';
        }
        for($z = 0; $z < $x * 2 +1; $z++) {
            echo 'x';
        }
        echo "\n";
    }


}