Reputation: 13
I loop through a multidimensional array to echo the first five values of every "row" as a table. As far as that, it works perfectly:
"<table>";
for ($row = 0; $row < $index_number; $row++) {
echo "<tr>";
for ($col = 0; $col < 5; $col++) {
echo "<td>".$tablevalue[$row][$col]."</td>";
}
echo "</tr>";
}
echo"</table>";
Now I want to display numbers 1 to 3 and then 8 and 9 again. Neither one for loop inside another nor two seperate loops work the way I want them to.
Thats what I tried so far:
echo "<table>";
for ($row = 0; $row < $index_number; $row++) {
echo "<tr>";
for ($col = 0; $col < 3; $col++ && $col2 = 8; $col2 < 10; $col2++) {
echo "<td>".$tablevalue[$row][$col]."</td>";
}
echo "</tr>";
}
echo"</table>";
Any ideas on how to make it work?
Upvotes: 0
Views: 40
Reputation: 79014
For your inner loop just use a conditional, if you have integer indexes starting at 0:
foreach($tablevalue[$row] as $col => $val) {
if($col < 3 || ($col > 7 && $col < 10)) {
echo "<td>$val</td>";
}
}
However, as you can see foreach
is much easier for the entire thing:
foreach($tablevalue as $row) {
echo "<tr>";
foreach($row as $col => $val) {
if($col < 3 || ($col > 7 && $col < 10)) {
echo "<td>$val</td>";
}
}
echo "</tr>";
}
If you don't have integer indexes starting at 0, then just foreach(array_values($tablevalue)...
and foreach(array_values($row)...
or you can slice what you want and implode
:
foreach($tablevalue as $row) {
echo "<tr><td>";
echo implode("</td><td>", array_slice($row, 0, 3, true) +
array_slice($row, 7, 2, true));
echo "</td></tr>";
}
Upvotes: 1