NitheesBavesh NitheesBavesh - 2 months ago 22
PHP Question

I want the following output using for loop in php

I want to display the output as like this

1 1
12 21
123 321
1234 4321
1234554321


Here is my php code

for($i=1;$i <= 5;$i++)
{
for($j=1;$j<=$i;$j++)
{
// print the result
echo "$j";


}
for($y=$i;$y<=$i;$y++)
{
echo '&nbsp;&nbsp;';
}
for($k=$i;$k>=1;$k--)
{

// print the result
echo "&nbsp;$k";}

echo "<br/>";
}


But I got the output like this

1 1
12 2 1
123 3 2 1
1234 4 3 2 1
12345 5 4 3 2 1


Please help me get an output like above.

Answer

try

for($i=1;$i <= 5;$i++) {
    for($j=1;$j<=$i;$j++) {
      echo "$j";
    }
    for($y=0;$y<(5-$i)*4;$y++) {
      echo '&nbsp;';
    }
    for($l=$i;$l>0;$l--) {
      echo "$l";
    }
    echo "<br/>";
}

output:-

1        1
12      21
123    321
1234  4321
1234554321

For browser view :- for($y=0;$y<(5-$i)*4;$y++) else correct way to going is for($y=0;$y<(5-$i)*2;$y++)