Home > Back-end >  Number Pattern PHP
Number Pattern PHP

Time:07-06

i will print number pattern like this :

1
12
123
1234
2
23
234
2341
3
34
341
3412
4
41
412
4123

My code :

for($i=1; $i<=4;   $i) {
    for($j=1; $j<=$i;   $j) {
        echo $j;
    }
    echo ("<br/>");
}
for($i=2; $i<=4;   $i) {
    for($j=2; $j<=$i;   $j) {
        echo $j;
    }
    echo ("<br/>");
}

I don't know how to print first number if max number is finish. Can anyone help me? Thank you

CodePudding user response:

You loop from 1 to 4, and subtract 4 if the value is bigger than 4.

This is for 2, 23, 234, 2341:

for ($i = 1; $i <= 4; $i  ) {
  for ($j = 1; $j <= $i; $j  ) {
    $value = $j   1;   // or  2, or  3
    echo $value > 4 ? $value - 4 : $value;
  }
  echo "\n";
}

And this would generate all output within one big loop:

$max = 4;

for ($start = 0; $start < $max; $start  ) {
  for ($i = 1; $i <= $max; $i  ) {
    for ($j = 1; $j <= $i; $j  ) {
      $value = $j   $start;
      echo $value > $max ? $value - $max : $value;
    }
    echo "\n";
  }
}
  • Related