How to display two table columns per row in php loop

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.

Leave a Comment