Printing a pattern without a nested loop in PHP


The output to my code should be:


I’m currently using this code with a nested for loop to get the result.

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

I need to be able to get the same result without the nested for loop, and I’m stumped. The only thing I want to use is a single for loop. Nothing else. No ifs, switches, or other loops.



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

Using this string accumulator removes the need for a second loop.

Answered By – CollinD

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published