2

I'm creating tables with 4 rows and 2 columns using this for loop:

   $row = 4; //Dynamic number for rows
   $col = 2; // Dynamic number for columns


   for($i=0;$i<$row;$i++){
      for($j=0;$j<$col;$j++){
        echo $i+$j.'</br>';
      }

  }

However, I cannot seem to get it to output 1-8 in numbers sequentially.

Would be grateful is someone knows how to do this?

Cheers

K

Ke.
  • 2,484
  • 8
  • 40
  • 78
  • 1
    Maximum $i will ever be is 3 and for $j = 1, so all you can get it 4. What are you trying to accomplish here? – sskoko Sep 04 '18 at 10:34

2 Answers2

2

You just need to do a bit of maths on the number output. As each value of $i represents a set of columns (each being $col long), I use $i*$col, add the column ($j), but as $j starts at 0, I just add 1 for the final value...

$row = 4; //Dynamic number for rows
$col = 2; // Dynamic number for columns

for($i=0;$i<$row;$i++){
    for($j=0;$j<$col;$j++){
        echo (($i*$col)+$j+1).'<br />';
    }
}

Which outputs...

1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • +1 from me for the right, simple answer... I just want to point out that there's an HTML error, it must be `
    ` (it was already wrong in the original post) ;-)
    – Francesco G. Sep 04 '18 at 11:08
0
$row = 4; //Dynamic number for rows
$col = 2; // Dynamic number for columns

for($i=0;$i<$row;$i++){
  for($j=0;$j<$col;$j++){
    echo $i*$col + $j.'</br>';
  }
}