How can I arrange numbers in this side-to-side pattern?

  • A+
Category:Languages

I am trying to make this pattern in PHP:

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

I tried this, but was unsuccessful:

$num = 0; for ($i=0; $i<=2; $i++) {       for ($j=1; $j<=5; $j++) {           $num = $j - $i+$num;         echo $num."";          $num--;     }       echo "</br>";   } 

Can anyone help me please?

Thanks in advance...

 


Here is the simplest and fastest code I was able to make using two loops. It's easier with three loops and there are multiple ways to achieve this but here is the simplest one according to me.

<?php  $num = 1; $change = true; $cols = 5; $rows = 5;  for ($i = 0; $i < $rows; $i++) {     if (!$change) {         $num += ($cols - 1);     }      for ($j = 0; $j < $cols; $j++) {         echo $num . " ";         if (!$change) {             $num--;         } else {             $num++;         }     }      if (!$change) {         $num += ($cols + 1);     }      $change = !$change;     echo "<br>"; } 

NOTE: You have to define the number of columns in $cols variable. It will work with any case.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: