-1

I need to generate about 100000 unique code. I have tried following code. But it is getting slower. Can anybody suggest me how can I make it faster, soon I have to generate unique code of 1M.

$uniqueArray = array();
for($i = 1; $i <= 100000; $i++) {
    $pass = substr(md5(uniqid(mt_rand(), true)) , 0, 6);

    if (!in_array($pass, $uniqueArray)) {
       $uniqueArray[] = 'AB' . $pass;
    }
}
nas
  • 2,289
  • 5
  • 32
  • 67
  • 1
    Your unique code needs to have only 6 chars? If you increase the size, it's virtually impossible to have a collision, so you skip that `in_array`. – Elias Soares Nov 20 '19 at 10:43
  • Possible duplicate of [PHP: How to generate a random, unique, alphanumeric string?](https://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string) – Tordek Nov 20 '19 at 10:43
  • 1
    Also you don't need to md5 the uniqid(). It will ruin the uniqueness of the uniqid(). – Elias Soares Nov 20 '19 at 10:49

2 Answers2

2

As is, your code is not guaranteed to generate a given amount of unique values. You would need to keep track of the actual number of values in $uniqueArray to be sure.

That said, you can speed up the generation by not searching in the array but by using the array as a map (key => value), e.g.:

<?php
declare(strict_types=1);

error_reporting(-1);
ini_set('display_errors', 'On');

/**
 * @return string
 */
function createUniqueCode(): string
{
    // ...or any other implementation
    return 'AB' . substr(md5(uniqid((string)mt_rand(), true)), 0, 6);
}

$uniqueMap = [];
$n         = 10000;

while ($n > 0) {
    $pass = createUniqueCode();

    if (!isset($uniqueMap[$pass])) {
        $uniqueMap[$pass] = true;
        $n--;
    }
}

$codes = array_keys($uniqueMap);
echo count($codes);
Yoshi
  • 54,081
  • 14
  • 89
  • 103
0
<?php
$count = 100000;
$uniqueArray = range(0,$count-1);
shuffle($uniqueArray);
array_walk($uniqueArray,function(&$v,$k){$v = "AB".sprintf("%06d",$v);});

Runtime <100ms for 100000 values.

Note: If you need the full uniqueness of the values then use the pure uniqueid and dont reduce the results with substr() or other functions.

jspit
  • 7,276
  • 1
  • 9
  • 17