Search code examples
phpcycle

Why does this PHP function cycle endlessly?


function nonrecgen($min, $max, $amount) {
for($i=0;$i<$amount;$i++) {

$NrArray[$i] = rand($min,$max);
echo $NrArray[$i];
do  {
    for($j=0;$j<=$i;$j++) {
      if ($NrArray[$j] == $NrArray[$i]) {
      $NrArray[$i] = rand($min,$max);   }     
                          }
       $Reccuring = false;
   if ($i > 0) {
    for($k=0;$k<=$i;$k++) {
      if ($NrArray[$k] == $NrArray[$i]) {
       $Reccuring = true;               }
                          }
               }
    }
while ($Reccuring = true);
                          }
Return $NrArray;                                        
                                        }

$Test = nonrecgen(0,1,2);
print_r($Test);

I wanted to look into how to generate an array of nonreccuring numbers and while this is certainly not the most efficient way I believe, I can't seem to figure out why it loops endlessly on the first iteration. I tried logical analysis over and over, but there has to be something I'm missing.


Solution

  • Other than the = to == you were also resetting the $Recurring in the wrong place:

    <?
    function nonrecgen($min, $max, $amount) 
    {
        for($i=0;$i<$amount;$i++) 
        {
            $NrArray[$i] = rand($min,$max);
            do  
            {
                for($j=0;$j<=$i;$j++) 
                {
                    if ($NrArray[$j] == $NrArray[$i]) 
                    {
                        $NrArray[$i] = rand($min,$max);  
                    }     
                }
                if ($i > 0) 
                {
                    for($k=0;$k<=$i;$k++) 
                    {
                        if ($NrArray[$k] == $NrArray[$i]) 
                        {
                            $Reccuring = true;               
                        }
                    }
                }
                $Reccuring = false;
            }
            while ($Reccuring == true);
        }
        return $NrArray;                                        
    }
    $Test = nonrecgen(0,2,5);
    echo "<pre>";
    print_r($Test);
    ?>