0

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?

1
  • Did you give up? Commented Mar 2, 2021 at 4:24

1 Answer 1

1

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

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.