0

You got the array:
$tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];

I want to make table with values from array tab.
Table must be max 4-columns.
Its should look like this:

1 2 3 4
5 6 7 8
9

My example code (not working):

$tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$max = count($tab);

// 1 FOR - ROWS
echo "<table>";
    for ( $i = 0; $i < $max; $i+=4 )
    {
    echo "<tr>";
        // 2 FOR - COLUMNS
        for ( $x = $i; $x < 4; $x++ ) //our array is 9-elemented, in third row $x going to be out of index
        {
            printf('<td>%s</td>', $tab[$x]);
        }
    echo "</tr>";
    }
echo "</table>";

4 Answers 4

2
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunks = array_chunk($arr, 4);
echo '<table>';
foreach ($chunks as $chunk) {
    echo '<tr>';
    foreach ($chunk as $val) {
        printf('<td>%s</td>', $val);
    }
    echo '</tr>';
}
echo '</table>';
Sign up to request clarification or add additional context in comments.

3 Comments

Forgot completely about array_chunk. Okay, I'm officially rusty on PHP.
with array_chunk code is more pretty, but slowly, so solution with mod operator completely correct and foreach is better against for ;)
I dont think that the solution can be easy (dont know about function). That's what i want. Very thanks!
1
$tab = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$max = count($tab);

echo "<table>";
    echo "<tr>";
    for ( $i = 0; $i < $max; $i++ ) {
        if ($i > 0 && $i % 4 == 0) {
            echo "</tr><tr>";
        }
        printf('<td>%s</td>', $tab[$i]);
    }
    echo "</tr>";
echo "</table>";

Comments

1
<?php
    $tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    $i=1;
    echo '<table>'
    foreach($tab as $key => $val){
        if ($i==1) echo '<tr>'
        if($i%4==0){ $i=0; echo "<td>$val</td> </tr>";}
        else {
          echo "<td> $val </td>";
        }
        $i++
    }
    echo '</table>'
?>

Comments

1
$tab = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$max = count($tab);
echo "<table>";
    for($i=0;$i<$max;$i=$i+4){
        echo '<tr>';
            for($x=0;$x<4;$x++){
                if($x+$i>=$max){
                    continue;
                }else{
                    echo '<td>'.$tab[($x+$i)].'</td>';
                }
            }
        echo '</tr>';
    }
echo "</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.