Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

php

numbers

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...

like image 963
Smit Pipaliya Avatar asked Feb 12 '19 14:02

Smit Pipaliya


3 Answers

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.

like image 103
p01ymath Avatar answered Oct 18 '22 02:10

p01ymath


<?php
   $numbers = array(1, 2, 3, 4);
   $flag = false;
   result($numbers, $flag);

   function printMe(&$array2){
    foreach($array2 as $index => $value){
    echo $value."   ";
    }
    echo "<br>";
   }

   function reverse(&$num, $flag)
   {
    if($flag){
    array_reverse($num, true);
    }
    $flag = false;
   }
    function add(&$array){
          $array[0] += 4;     
          $array[1] += 4; 
          $array[2] += 4; 
          $array[3] += 4; 
    }
    function result($numbers, $flag){
        for($i = 0; $i < 3; $i++ )
        {
            reverse($numbers, $flag);
            printMe($numbers);
            add($numbers);
        }
    }

?>
like image 38
Di_Moore Avatar answered Oct 06 '22 11:10

Di_Moore


Using a for loop and range with array_reverse:

https://3v4l.org/7QMGl

<?php

$number = 25;
$columnCount = 4;

for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
    $range = range($i, $i+$columnCount - 1);

    if($loopCounter % 2 === 0) {
        $range = array_reverse($range);
    }

    foreach($range as $n) {
        echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
    }

    echo "\n";

}

We are increasing $i by the $columnCount on every iteration so we can always generate an array of the range of the numbers that have to be output in this row. That makes it very simple and clear if we have to reverse the numbers of the row.

str_pad helps us to maintain the correct spacing for e.g. single digits

Note: You might have to swap echo "\n"; for echo "<br>"; if you are looking at the output in a browser.

like image 7
Xatenev Avatar answered Oct 18 '22 01:10

Xatenev