Home > Software engineering >  Multi For loop php
Multi For loop php

Time:01-15

How to use multi for loop with array.

I'm trying to iterate over the contents of an array. This is the code I have tried.

<?php

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

for($i = 0; $i < 5; $i  ){
    echo $arr[$i];
    for($j = 0; $j < $i; $j  ){
        echo $arr[$j];
    }
    echo "<br />";
}
echo "<br/>";
for ($i = 0; $i <= count($arr); $i  ){
    if ($i%3 == 0){
        echo $arr[$i-1] . "  " . "<br />";
    } else {
        echo $arr[$i-1] . "  ";
    }
}

this is the result i got

1
2 1
3 1 2
4 1 2 3
5 1 2 3 4

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

I want to display a result like this and how it works:

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

1 | 6 | 11
2 | 7 | 12
3 | 8 | 13
4 | 9 | 14
5 | 10 | 15

Thank you

CodePudding user response:

Two separate questions:

The first one, I'd do like this:

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
$prev =0;
for ($i=1; $i<=5; $i  ) {  
   print implode(" ", array_slice($arr, $prev, $i)) . "<br>\n";
   $prev  = $i;
}

You could replace the array_slice() with a for loop if that makes you happier. The second one:

$cols = 3;
$rows = floor(count($arr)/$cols);

for ($i = 0; $i < $rows; $i  ) {
  for ($j=0; $j<=$cols; $j  ) {
    print $arr[$i $j*$rows] ?? ' ';
    if ($j < ($cols-1)) print " | ";
  }
  print "<br>\n";
}
  •  Tags:  
  • Related