Chris
Chris

Reputation: 115

Else If - amount of table rows php

I want to include a table with in dependency of the amount of row numbers of a specific table. I count the row numbers via

$html = file_get_html('URL');    
$table = $html->find('table', 1);
     // Row Numbers
        $tr_count = $table->find('tr'); // get the total <tr> tag count
        $count = count($tr_count);

Now I want to include the table with an if-function. There are limited possibilities. There are always at least 3 rows, at max there are 6. So I thought if I make for each case an if-clause it would work, but no. Can you take a look at the code please?

// Include Table
            echo '<table>
              <tbody>
                <tr>
                  <td>row 1</td>
                </tr>
                <tr>
                  <td>row 2</td>
                </tr>
                <tr>
                  <td>row 3</td>
                </tr>';
// If 3 end Table
            if ($count = 3) {
            echo '</tbody></table>';
            }
// if 4 include row 4 and end table
            elseif ($count = 4) {
            echo '<tr><td>row 4</td></tr></tbody></table>';
            }
// if 5 include row 4 and 5 and end table
            elseif ($count = 5) {
            echo '<tr><td>row 4</td></tr><tr><td>row 5</td></tr></tbody></table>';
            }
// else (there can only be 6 max) include row 4,5 and 6 and close table
            else {
echo '<tr><td>row 14</td></tr><tr><td>row 15</td></tr><tr><td>row 16</td></tr></tbody></table>';
            }

Upvotes: 1

Views: 165

Answers (1)

DrRoach
DrRoach

Reputation: 1356

Try using a switch:

switch($count) {
    case 3:
        echo '</tbody></table>';
        break;
    case 4:
        echo '<tr><td>row 4</td></tr></tbody></table>';
        break;
    case 5:
        echo '<tr><td>row 4</td></tr><tr><td>row 5</td></tr></tbody></table>';
        break;
    case $count > 5:
        echo '<tr><td>row 14</td></tr><tr><td>row 15</td></tr><tr><td>row 16</td></tr></tbody></table>';
        break;
}

More can be done with the switch to remove the need for your repeating of code but I'll leave that as extra homework.

Upvotes: 1

Related Questions