Skip to content

Instantly share code, notes, and snippets.

@edmhs
Created May 29, 2017 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edmhs/bd15c63b712e3558c0e1b6c1dbc5d580 to your computer and use it in GitHub Desktop.
Save edmhs/bd15c63b712e3558c0e1b6c1dbc5d580 to your computer and use it in GitHub Desktop.
Generate unique coupon codes
<?php
//prefi for coupons
$prefix = 'ABCD';
//how many codes you need?
$need = 200;
$codes = array();
while(count($codes)!=$need){
//choose format
$code = $prefix.getRandomStringNUMS(2).getRandomStringCHARS(2).getRandomStringNUMS(2).getRandomStringCHARS(2);
$codes[$code] = $code;
}
function getRandomStringCHARS($length = 3){
$validCharacters = "ABCDEFGHIJKLMNOPQRSTUXYVWZ";
$validCharNumber = strlen($validCharacters);
$result = '';
for($i =0; $i < $length; $i++)
{
$index = mt_rand(0,$validCharNumber-1);
$result .= $validCharacters[$index];
}
return $result;
}
function getRandomStringNUMS($length = 3){
$validCharacters = "1234567890";
$validCharNumber = strlen($validCharacters);
$result = '';
for($i =0; $i < $length; $i++)
{
$index = mt_rand(0,$validCharNumber-1);
$result .= $validCharacters[$index];
}
return $result;
}
foreach($codes as $c){
echo $c."\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment