Reputation: 1329
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;
}
Upvotes: 1
Views: 162
Reputation: 8643
Your original code recurses, but i don't think you need to do that.
$start = 0;
$count = 10;
$codes = [];
$another = $this;
for ($i=$start; $i < $count; $i++) {
//do not pass $codes as a reference here
$getUniqueCode = function ($codes) use ($another)
{
$newCode = $another->genRandomCode();
while(in_array($newCode, $codes))
{
echo "Regenerate on DUPLICATE FOUND - $newCode <br/>";
}
return $newCode;
};
$newCode = $getUniqueCode($codes);
if (\in_array($newCode, $codes)) {
echo "still DUPLICATE Exist - $newCode <br/>";
}
array_push($codes, $newCode);
}
Arguably however, a better way to handle a coupon system like this is to generate the possible coupon codes beforehand, store them in a database, and select one at random for activation. this guarantees a unique code, and lets you keep track of which codes you have used so far.
Upvotes: 1