Skip to content
Advertisement

Stuck with the number pattern printing in PHP

Stuck with the number pattern printing logic. Let me know what i am doing wrong as my file is simply going on execution without giving me a pattern.

My Code —

<?php

$num = 4;

for( $j=1 ; $j <= $num ; $j++ )
{
    for( $i=$j ; $i < $num-1 ; $i++ )
    {
    echo "&nbsp;";
    }

    for( $j ; $j >= 1 ; $j-- )
    {
    echo $j."&nbsp;";
    }

echo "<br />";
}

Pattern to achieve —

   1
  21
 321
4321

UPDATE

After applying new changes following are the screenshots —

On STAR USEAGE

ON BLANK USAGE

Advertisement

Answer

Your error is in the last for, that should not exist since you are already looping.

And create a new variable which will hold the printed text for the next increment.

<?php

$num = 4;
$wrap = '';

for( $j=1 ; $j <= $num ; $j++ )
{
    for( $i=$j ; $i < $num ; $i++ )
    {
        echo "&nbsp; ";
    }

    echo $wrap = $j.$wrap;
    echo "<br />";
}
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement