Search code examples
phparraysrandomhtml-tablenested-loops

Decrement in Nested Loop Affects Outer Loop


Trying to display random numbers from 1-10, seven times per fourteen(rows) each number is assigned a different background color. I thought of using 2 nested loops, but it's not working as expected. The page loads for a long time then: "Fatal error: Maximum execution time of 30 seconds exceeded in ..."

I tried to remove the decrement on the inner loop and the problem disappears but I don't get the expected results. Thanks in advance.

$colors = array("grey","white","yellow","red","blue","green","brown","purple","orange","black");
$previousNum = array();
$k = 0;
echo '<table>';
while ($k < 15){
    $k++;
    echo '<tr>';
    for($i = 0; $i < 7; $i++){
        $randNum = mt_rand(1, 10);
        if(!in_array($randNum, $previousNum)){
            echo '<td style="background-color: '.$colors[$randNum-1].'; padding: 10px;">';
            echo $randNum;
            echo '</td>';    
            array_push($previousNum, $randNum);
        }else{
            $i--;
        }
    }
    echo '</tr>';
}

Solution

  • Try this, hope this will help you out. The problem was that you were,

    1. initializing array($previousNum = array();) out of while loop

    <?php
    
    $colors = array("grey", "white", "yellow", "red", "blue", "green", "brown", "purple", "orange", "black");
    $k = 0;
    
    echo '<table>';
    
    while ($k < 15)
    {
    
        echo '<tr>';
    
        $previousNum = array();
        for ($i = 0; $i < 7; $i++)
        {
            $randNum = mt_rand(1, 10);
            if (!in_array($randNum, $previousNum))
            {
    
                echo '<td style="background-color: ' . $colors[$randNum - 1] . '; padding: 10px;">';
                echo $randNum;
                echo '</td>';
                array_push($previousNum, $randNum);
            } 
            else
            {
                $i--;
            }
        }
    
        $k++;
        echo '</tr>';
    }
    

    Output:

    enter image description here