I'm trying to generate a set of unique Alpha Numeric code in php. I tried using anonymous function and closures.
Here when I generate more than 1000 codes, there are changes of codes getting duplicate. So I tried to generate a new code if any duplicate found.
Below is my code which isn't working as expected, I'm getting "still DUPLICATE Exist" a few times and its not regenerating code even a single time.
$start = 0;
$count = 10;
$codes = [];
$another = $this;
for ($i=$start; $i < $count; $i++) {
$getUniqueCode = function (&$codes) use ($another, &$getUniqueCode) {
$newCode = $another->genRandomCode();
if (in_array($newCode, $codes)) {
echo "Regenerate on DUPLICATE FOUND - $newCode <br/>";
return $getUniqueCode($codes);
} else {
return $newCode;
}
};
$newCode = $getUniqueCode($codes);
if (\in_array($newCode, $codes)) {
echo "still DUPLICATE Exist - $newCode <br/>";
}
array_push($codes, $newCode);
}
private function genRandomCode()
{
$str = "ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
$randInt = rand(1000000, 9999999);
$randString = "";
for ($i=0; $i < 6; $i++) {
$randRem = $randInt % 36;
$randInt = $randInt / 36;
$randString .= $str[$randRem];
}
return $randString;
}