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.
<?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);
}
}
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With