I'm trying to generate an array of random numbers from 0-n then shuffle (but ensure that the keys and values DO NOT match).
For example:
0 => 3
1 => 2
2 => 4
3 => 0
4 => 1
Note that both keys and values are from 0-4 but none of the keys and values are the same.
Any thoughts?
A even shorter solution:
$random_number_array = range(0, 100);
shuffle($random_number_array );
$random_number_array = array_slice($random_number_array ,0,10);
print_r($random_number_array);
Result will be:
[0] => 53
[1] => 6
[2] => 16
[3] => 59
[4] => 8
[5] => 18
[6] => 62
[7] => 39
[8] => 22
[9] => 26
$max = 5;
$done = false;
while(!$done){
$numbers = range(0, $max);
shuffle($numbers);
$done = true;
foreach($numbers as $key => $val){
if($key == $val){
$done = false;
break;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With