Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 743

PHP create pyramid pattern string contain numbers

I want result like below that rows can be dynamic.

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

I tried like below

$a=5;
for ($i=1; $i<=$a; $i++){
   for ($j=1; $j<=$i; $j++){
      echo $j; 
   }
   echo "</br>";
}

Getting result like below.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Please help me.

Upvotes: 0

Views: 249

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94672

I think you need a seperate variable to hold the counter

<?php
$a=5;
$num = 1;

for($i=1;$i<=$a;$i++){
   for($j=1;$j<=$i;$j++){
      echo $num++;  // echo and increment the counter
   }
   echo "</br>";
}
?>

Upvotes: 4

Jigar Shah
Jigar Shah

Reputation: 6223

just few modification needed

$number = 1; // counter
$a=5;
for($i=1;$i<=$a;$i++){
   for($j=1;$j<=$i;$j++, $number++){ // increment number 
      echo $number. ' '; // space 
   }
   echo "</br>";
}

Upvotes: 0

Related Questions