phparraysfor-looparray-key-exists

Pattern Output, stuck


Pretty new to all this, but here i go...

I need to make 2 patterns using a table (without borders) and for-loops:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6

I did work this one out with (probably not the easiest way tho, but it works):

<table>
        <b>Patroon I</b>
        <?php
            $pattern = array();
            for($pyramid = 1; $pyramid <=6; $pyramid++){
                $pattern[$pyramid] = $pyramid;
                echo "<tr>
                        <td class='td1'>" . $pattern[1] . "</td>";
                        if(array_key_exists(2, $pattern)){
                            echo "<td class='td1'>" . $pattern[2] . "</td>";
                        }
                        if(array_key_exists(3, $pattern)){
                            echo "<td class='td1'>" . $pattern[3] . "</td>";
                        }
                        if(array_key_exists(4, $pattern)){
                            echo "<td class='td1'>" . $pattern[4] . "</td>";
                        }
                        if(array_key_exists(5, $pattern)){
                            echo "<td class='td1'>" . $pattern[5] . "</td>";
                        }
                        if(array_key_exists(6, $pattern)){
                            echo "<td class='td1'>" . $pattern[6] . "</td>";
                        }
                echo "</tr>";
            }
        ?>
</table>

and the other pattern

1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

Which I can't seem to figure out.
I tried to turn the previous code around, tried rsort($pattern), tried a lot of IF-statements, and now im stuck :S

Anyone has a hint for me?

Thanks!


Solution

  • You don't need any array or fancy function, just two nested for loops.

    <table>
            <?php
                // 1
                // 1 2
                // 1 2 3
                // ...
                $rows = 6;
                for ($row = 1; $row <= $rows; $row++) {
                    echo "<tr>";
                    for ($col = 1; $col <= $row; $col++) {
                        echo "<td class='td1'>" . $col . "</td>";
                    }
                    echo "</tr>";
                }
            ?>
    </table>
    
    <br />
    
    <table>
            <?php
                // 1 2 3 4 5 6
                // 1 2 3 4 5
                // 1 2 3 4
                // ...
                $rows = 6;
                for ($row = $rows; $row > 0; $row--) {
                    echo "<tr>";
                    for ($col = 1; $col <= $row; $col++) {
                        echo "<td class='td1'>" . $col . "</td>";
                    }
                    echo "</tr>";
                }
            ?>
    </table>
    

    Add the following code before the closing row tag for balanced table rows.

    if ($span = $rows - $row)
        echo  "<td colspan='$span'></td>";