Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Number Pattern PHP

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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";
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading