Search code examples
phpregexloopsnestedcontrols

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("*");
    }
        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.

Thanks!


Solution

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

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