13

I would like to display data, two columns per row during my foreach. I would like my result to look like the following:

 <table>
 <tr><td>VALUE1</td><td>VALUE2</td></tr>
 <tr><td>VALUE3</td><td>VALUE4</td></tr>
 <tr><td>VALUE5</td><td>VALUE6</td></tr>
 </table>

Any help would be greatly appreciated.

4 Answers 4

48

You can use array_chunk() to split an array of data into smaller arrays, in this case of length 2, for each row.

<table>
<?php foreach (array_chunk($values, 2) as $row) { ?>
    <tr>
    <?php foreach ($row as $value) { ?>
        <td><?php echo htmlentities($value); ?></td>
    <?php } ?>
    </tr>
<?php } ?>
</table>

Note that if you have an odd number of values, this will leave a final row with only one cell. If you want to add an empty cell if necessary, you could check the length of $row within the outer foreach.

Sign up to request clarification or add additional context in comments.

1 Comment

Just used this on a project I was working on. Worked great!
12
$i=0;
foreach ($x as $key=>$value)
  {
  if (fmod($i,2)) echo '<tr>';
  echo '<td>',$value,'</td>';
  if (fmod($i,2)) echo '</tr>';
  $i++;
  }

this will output TR (row) each second time

ps: i haven't tested the code, so maybe you will need to add ! sign before fmod, if it doesn't output TR on first iteration, but on second iteration in the beginning...

3 Comments

Thank you, this works great. Yeah I had to add !fmod for the first.
@FredStevens-Smith: Instead of saying 'Does not work', why don't you elaborate a little. Why doesn't it work? Have you received an error? How could it be bettered?
Your code appears to contain a mistake; $i++ should have been moved up one line.
1

This would give you great table and for loop concept--

<table border="1" cellspacing="0" cellpadding="2">

<?php

     for($x=1; $x<=20; $x++)
        {
         echo "<tr>";
        for($y=1; $y<=20; $y++)
           {
          echo "<td>";
          echo $x*$y;
          echo "</td>"; 
           }
         echo "</tr>";
        }
?>
</table>

1 Comment

I don't think this is exactly what the OP wanted... Read the question.
-1
<table>
<?php
   $i=0;
   foreach ($x as $key=>$value)
   {
      if (!$i%2) echo '<tr>';
      echo '<td>',$value,'</td>';
      if ($i%2) echo '</tr>';
      $i++;
   }
?>
</table>

1 Comment

it should = if ($i%2 == 0) echo '<tr>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.