Elda Backa Elda Backa - 5 years ago 355
PHP Question

Outputting 20 different random numbers within a range using php

I've created this code to output 20 random numbers from 5 to 100 in PHP. All the numbers must be different from each other.
While executing I'm taking this error

enter image description here

This is my code:

<?php

$a=array();
while(count($a)<20){
$found=false;
$random=rand(6,100);
for($i=0;$i<=count($a);$i++){
if($a[$i]==$random){
$found==true;
break;
}
}
if(!$found)
$a[count($a)]=$random;


}
echo $a;

?>


Can someone help me to deal with this error? Thanks!

Answer Source

Try this simple code

<?php  
$a=array();
while(count($a)<20){
   $random=rand(6,100);
   if(!in_array($random, $a)){
      $a[] = $random;
   }

}
print_r($a);
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download