Home » Php » How to echo an array into columns in php

How to echo an array into columns in php

Posted by: admin February 25, 2020 Leave a comment

Questions:

Ok so I have an array full of values and I want to echo them in a specific way.

This is my code so far:

<?php foreach( $names as $i ) {
  echo $i."<br>";
}?>

So at the moment I am stacking each value under one another. But I want to change it into columns.

I want it to display like this:

Name 1 Name 2

Name 3 Name 4

And so on…
How can I achieve this?

How to&Answers:

Iterate through your array and build a HTML form from it. Since you’d like 2 rows, here is an example:

<?php if($names) :
    echo '<table>';
    $counter = 1;
    foreach($names as $i) :
        if($counter%2 !== 0) {
            // Start new row
            echo '<tr>';
        }
        echo '<td>' . $i . '</td>';
        if($counter%2 == 0) {
            // End row
            echo '</tr>';
        }
        $counter++;
    endforeach;
    if($counter%2 == 0) {
        // Last empty cell
        echo '<td></td></tr>';
    }
    echo '</table>';
endif;
?>

Demo:
https://3v4l.org/knGae