Search code examples
phpfor-looplogic

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


Solution

  • 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 />";
    }
    ?>