0

I test php array_rand function and find it has repeat result ,this is my code:

    $arr = range(1,10000);
    $max = 200;
    $time = 0;
    while($time < $max){
        echo array_rand($arr).'<br>';
        $time++;
    }

And this is result:

enter image description here

You can see it keeps output repeat array index, and I am confused why it works like this, it is supposed to pick a random index.

3
  • 1
    Running the same code for me produces truly random data: 3v4l.org/t8bCd. You must have something else interfering. Commented Aug 25, 2017 at 2:45
  • I didn't have any repeating number either, but provided an answer that might work for you. Commented Aug 25, 2017 at 2:48
  • In 10000, you want to get 200 is not so good(large amount for that range) !! Commented Aug 25, 2017 at 2:58

3 Answers 3

1

You could make sure they don't repeat by doing something like this:

$arr = range(1,10000);
$max = 30;
$time = 0;
$used = array();
while($time < $max){
    $num = array_rand($arr);
    if( ! in_array($num, $used) ){
        echo $num . '<br>';
        $used[] = $num;
        $time++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to use while ! array_rand accept max random keys number as second parameter .

$arr = range(1,10000);
$max = 200;
$ran = array_rand($arr,$max);
var_dump($ran); // random keys
//tested with origin array $arr
//foreach($ran as $key) {
//    echo $arr[$key]."<br>"; 
//}

Comments

0

Because random values are not unique. Unless you really have to use numbers between 1 and 10,000, why not consider the following functions to get unique ids?

$number_and_letters = uniqid(); 
OR 
$numbers_only = hexdec(uniqid());

Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.