What is the best way to generate 6 random numbers from 1-49 in PHP without duplicates and keeping the numbers unsorted?
To generate 6 random numbers from 1-49 without duplicates and keeping the numbers unsorted, one approach is to use an array to keep track of the generated numbers and check for duplicates before adding a new number. This can be achieved by using a while loop to generate random numbers until the array contains 6 unique numbers. Additionally, the shuffle function can be used to keep the numbers unsorted.
$randomNumbers = [];
while(count($randomNumbers) < 6){
$randomNumber = mt_rand(1, 49);
if(!in_array($randomNumber, $randomNumbers)){
$randomNumbers[] = $randomNumber;
}
}
shuffle($randomNumbers);
print_r($randomNumbers);
Related questions
-
Unix timestamps date/time calculations PHP developers
-
try-catch PDO exceptions
-
file permissions PHP scripts security vulnerabilities