-1

I have an array that I am echoing to a table but I can't seem work out how to refactor my code efficiently to increment my array values automatically. I'm new to php but am sure that this can be done.

<tr>
<td><?php echo $arrName[0]; ?> </td>
<td><?php echo $arrName[1]; ?> </td>
<td><?php echo $arrName[2]; ?> </td>
<td><?php echo $arrName[3]; ?> </td>
<td><?php echo $arrName[4]; ?> </td>
<td><?php echo $arrName[5]; ?> </td>
<td><?php echo $arrName[6]; ?> </td>
<td><?php echo $arrName[7]; ?> </td>
</tr>

how and where do I create a variable that can store the starting value and then how do I increment that value after each line?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
cinameng
  • 313
  • 4
  • 14
  • 4
    [foreach](http://php.net/manual/en/control-structures.foreach.php)? – peterm Aug 02 '17 at 19:10
  • What do you actually mean by "a starting value" or "increment that value"? Either the answer to your question is trivial, or you ask something that does not really get clear from the way _how_ you ask it. – arkascha Aug 02 '17 at 19:11
  • "a starting value" would be 0 and "increment that value" would be to +1 after each use, so I'm simply replacing the [0] with [i]. – cinameng Aug 02 '17 at 19:23

1 Answers1

4

Use foreach():

<?php 
 foreach($arrName as $val){?
   <tr>
      <td><?php echo $val; ?> </td>
   </tr>
<?php }?>

The advantage is that it will take care of indexes of array automatically.

What you asked in a comment (create new row after each 7 elements of the array), you can do as follows:

<?php 

$arrName = array_chunk($arrName,7);
foreach($arrName as $val){
  echo "<tr>";
  foreach($val as $v){
    echo "<td>".$v."</td>";
  }
  echo "</tr>";
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98