Search code examples
phparrayssplitbreak

Break PHP array into 3 columns


I'm trying to break a PHP array into 3 columns (has to be columns, not rows) so it would look something like this:

Item 1     Item 2     Item 3
Item 4     Item 5     Item 6
Item 7     Item 8     Item 9
Item 10................

The best approach I can think of would be to break the main array into 3 arrays, 1 for each column although I can't work out the best approach to do this - more specifically the criteria I could use to generate the 3 arrays.


Solution

  • I would use this:

    $i = 1;
    foreach ($array as $value) {
      if ($i % 3 === 0) {
            echo $value . '<br />';
        }
       $i++;
    }
    

    Or when using html table:

    <table>
    <tr>
       <?php 
       $i = 0;
       foreach ($array as $value) {
          if ($i % 3 === 0) {
                echo '</tr><tr>';
            }
          echo "<td>" . $value . "</td>";
          $i++;
       }
       ?>
    </tr>
    </table>