kiki
kiki

Reputation: 3

Single php array to html table

The idea is to print an html table from this array:

$arr = ['1','2','3','4,'5,'6','7','8','9'];

I expect my table to be something like:

1 2 3

4 5 6

7 8 9

I tried a lot but I couldn't find an idea to do this.

My idea was to break each three element but I need something smarter.

Upvotes: 0

Views: 119

Answers (3)

$arr = ['1','2','3','4','5','6','7','8','9'];

$from=0; //index from of arr
$number=3; //number cell per row
echo "<table border='1'>";
while($row=array_slice($arr,$from,$number)){
    echo "<tr>";
    foreach($row as $cell) {
        echo "<td>$cell</td>";   
    }
    echo "</tr>";
    $from+=$number;
}
echo "</table>";

Upvotes: 1

Ismail RBOUH
Ismail RBOUH

Reputation: 10470

You can use array-chunk like this:

$arr = ['1','2','3','4','5','6','7','8','9'];

echo "<table>";
foreach(array_chunk($arr, 3) as $row) {
    echo "<tr>";
    foreach($row as $cell) {
        echo "<td>$cell</td>";   
    }
    echo "</tr>";
}
echo "</table>";

Upvotes: 1

Chris
Chris

Reputation: 391

<?php
$arr = ['1','2','3','4','5','6','7','8','9'];
print "<table>\n";
foreach(array_chunk($arr, 3) as $row) {
        print "<tr>";
        foreach($row as $col) {
                print "<td>";
                print $col;
                print "</td>";
        }   
        print "</tr>\n";
}
print "</table>";
?>

Upvotes: 0

Related Questions