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 ' ';
}
for($k=$i;$k>=1;$k--)
{
// print the result
echo " $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.
try
for($i=1;$i <= 5;$i++) {
for($j=1;$j<=$i;$j++) {
echo "$j";
}
for($y=0;$y<(5-$i)*4;$y++) {
echo ' ';
}
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++)
Did you ever here about the PHP functions str_repeat
and range
?
http://php.net/manual/en/function.str-repeat.php. http://php.net/manual/en/function.range.php
With it you can print your
character like this:
echo str_repeat(' ', (5 -$i) *4);
Complete code
$count = 5; // count oft rows and oft iterated numbers
for ($i = 1; $i <= $count; $i++) {
echo implode('', range(1, $i));
echo str_repeat(' ', ($count -$i) *4);
echo implode('', array_reverse(range(1, $i)));
echo '<br />';
}
How about this?
for($i=1;$i<=5;$i++){
echo substr("12345", 0, $i);
echo str_repeat(5-$i, ' ');
echo str_reverse(substr("12345", 0, $i));
echo '<br>';
}
Try this:
for($i=1;$i <= 5;$i++)
{
for($j=1;$j<=$i;$j++)
{
echo "$j";
}
for($y=1;$y<=10-(2*$i);$y++)
{
echo ' ';
}
for($k=$i;$k>=1;$k--)
{
// print the result
echo "$k";
}
echo "<br/>";
}
OUTPUT:
1 1
12 21
123 321
1234 4321
1234554321
How about this with $y<= 2 * (5 - i)
,
for($i=1;$i <= 5;$i++) {
for($j=1;$j<=$i;$j++) {
echo "$j";
}
for($y=1;$y<= 2 * (5 - i); $y++) {
echo ' ';
}
for($k=$i;$k>=1;$k--) {
echo "$k";
}
echo "<br/>";
}
for ($counter=1;$counter<= 5;$conter++)
{
for ($j=1;$j<=$counter;$j++)
{
echo "$j";
}
for ($y=1;$y<=10-(2*$counter);$y++)
{
echo ' ';
}
for ($k=$counter;$k>=1;$k--)
{
echo "$k";
}
echo "<br/>";
}