Chan
Chan

Reputation: 1959

Get duplicated results in array_rand

<?php

class GenCrypt
{
    public function generate()
    {
        $hashSource = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
        $hashRandom = array_rand($hashSource, 12);
        shuffle($hashRandom);
        return implode(',', $hashRandom);
    }
}

$gen = new GenCrypt;
$count = array();

for ($i = 0; $i < 1000; $i++) {
    $count[] = $gen->generate();
}

var_dump(count($count));
var_dump(count(array_unique($count)));

I want to generate non-repetitive serial, so I use array_rand and shuffle to avoid duplicated data, but still got regular duplicated result, how to make it work?

Upvotes: 0

Views: 458

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

array_rand does not provide unique elements, it just picks up one or more randoms. You need to use array_unique to retrieve uniques. Also, shuffling the randoms is not necessary.

The summing up:

// $hashRandom = array_rand($hashSource, 12); // no promise on uniqueness

while(count($hashRandom = array_unique(array_rand($hashSource, count($hashSource)))) < 12) {
  /* insuccessful try, repeat */
}

// here $hashRandom has 12 uniques

In general, the first attempt should return 12 unique elements out of count($hashSource) randomly pulled. If not, the statement will be reevaluated until 12 are yielded. Hope it helps.

Upvotes: 1

Related Questions