How can I arrange numbers in this side-to-side pattern?
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.
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.
I decided to opt for the array_chunk
method to create 'rows' which I then iterate over.
$max = 13; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D
// Print the data.
foreach ($arr as $key => $row) {
// In case we are wrapping on the far side, this will prevent the row from
// starting on the left.
$row = array_pad($row, $cols, ' ');
// This will reverse every other row
$row = ($key % 2 === 0) ? $row : array_reverse($row);
foreach ($row as $value) {
$value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
echo "{$value} ";
}
echo "<br />";
}
Output:
1 2 3 4
8 7 6 5
9 10 11 12
13
I've given you some options too so that you can change the column lengths or the number of elements you want to produce.
The string padding won't be visible in your browser unless you wrap the output in <pre>
tags because browsers only show one space at a time.
Code in action