Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate array of random unique numbers in PHP

Tags:

php

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?

like image 747
Phil Avatar asked May 30 '12 21:05

Phil


2 Answers

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
like image 178
stonyau Avatar answered Nov 01 '22 08:11

stonyau


$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;
        }
    }
}
like image 5
AMayer Avatar answered Nov 01 '22 07:11

AMayer