deserthunter
deserthunter

Reputation: 25

php fun codeing

hey I make a simple php table using nested for loop ... and it will be like this...

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15

but the problem is , i can not print this value using a loop inside the column .. so what will be the solution ??? please

my code :

echo "<table border=1>\n";
for($row=1;$row<=3;$row++)
{
    echo "<tr>";
    for($col=1;$col<=5;$col++)
    {
        echo "<td>";
        echo "MY PROBLEM HERE...I cant print column numbers \n";
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table> \n";

Upvotes: 1

Views: 184

Answers (3)

HamZa
HamZa

Reputation: 14931

To save several loops:

$rows = 3;
$cols = 5;

$table = '<table border="1">';

for($i=1;$i<=$rows;$i++){
    $table .= '<tr><td>'.implode('</td><td>', range($cols*$i-$cols+1,$cols*$i)).'</td></tr>';
}

$table .= '</table>';
echo $table;

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

It's not $col + $row * 5 it has to be $row - 1

<?php
echo "<table border=1>\n";
for($row=1;$row<=3;$row++)
{
    echo "<tr>";
    for($col=1;$col<=5;$col++)
    {
        echo "<td>";
        echo $col + ($row-1) * 5;
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table> \n";

?>

Upvotes: 1

zakinster
zakinster

Reputation: 10698

echo "<table border=1>\n";
for($row=1;$row<=3;$row++)
{
    echo "<tr>";
    for($col=1;$col<=5;$col++)
    {
        echo "<td>";
        //echo "MY PROBLEM HERE...I cant print column numbers \n";
        echo $col + ($row - 1) * 5;
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table> \n";

Upvotes: 3

Related Questions