Search code examples
phploopsdecrement

How to prepend a decremented number to a string in a loop?


I am trying to make a triangular-shaped set of lines of decreasing numbers like this :

5
45
345
2345
12345

I tried this :

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

But it is printing the low number first and appending increasing numbers like this :

1
12
123
1234
12345

Solution

  • The inner loop needs to count down instead of up.

    You can either subtract the outer loop's variable from the limit to get the starting point and count down:

    for ($i = 0; $i < 5; $i++)
    {
        for ($j = 5 - $i; $j > 0; $j--)
        {
            echo $j;
        }
        echo "<br>";
    }
    

    or change the outer loop to count down from the limit as well.

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