0

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.

0

3 Answers 3

1

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>";
Sign up to request clarification or add additional context in comments.

Comments

1
$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>";

Comments

0
<?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>";
?>

Comments

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.