Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active July 1, 2022 01:04
Show Gist options
  • Save eusonlito/882893225189602ec41dcc062bc6ef63 to your computer and use it in GitHub Desktop.
Save eusonlito/882893225189602ec41dcc062bc6ef63 to your computer and use it in GitHub Desktop.
Generate unique strings. Tested over 100.000.000 iterations without duplicates.
<?php declare(strict_types=1);
if (!function_exists('uniqidReal')) {
/**
* @param int $length
*
* @return string
*/
function uniqidReal(int $length): string
{
$string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($string, rand(2, 5))), 0, $length);
}
}
<?php declare(strict_types=1);
ini_set('memory_limit', '-1');
set_time_limit(0);
$limit = 100000000;
$list = [];
for ($i = 0; $i < $limit; $i++) {
$id = uniqidReal(10);
if (isset($list[$id])) {
die($id.' found on position '.number_format($i));
}
$list[$id] = true;
}
die('Repeated ids not generated');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment