PrgmRNoob PrgmRNoob - 6 months ago 44
PHP Question

PHP asterisk triangle alignment

I'm new to web programming and recently started getting into PHP. I wrote a little code to produce a "right angle triangle". I recognize that using &nbsp is part of the solution but I've placed it in every possible place with no luck so any advice would be appreciated..Below you will find the coding/current output/desired output:

$x = 10;
while ( $x >= 1 ) {
$y=1;
while ($y <= $x) {
echo "*";
++$y;
}
echo "<br/>";
--$x;
}

output:
**********
*********
********
*******
******
*****
****
***
**
*


desire output:
**********
*********
********
*******
******
*****
****
***
**
*

Answer

You want 10 characters per line, n asterix and 10 - n spaces. Knowing this, you just need to add another loop inside to control how many spaces to output!

Something as simple as:

$x = 10;
while ( $x >= 1 ) {
    $spaces = 1;
    while($spaces <= 10 - $x)
    {
        echo "&nbsp";
        ++$spaces;
    }
    $y=1;
    while ($y <= $x) {
        echo "*";
        ++$y;
    }
    echo "<br/>";
    --$x;
}