Random codes generation
This function generates large number of unique codes.
It's useful for product package codes for promotional.
It's good idea to skip symbols that may be visually similar (like 1 and I).
Note that the function may require more memory than usual if the number of code is too big.
/**
* Generate large numbers of random unique codes with equal length.
* @author Samuil Banti
* @param array $symbols - Array with allowed symbols.
* @param int $num_codes - The number of codes needed.
* @return array $codes - An array with random unique codes.
* @license GNU/GPLv3<a href=" http://www.gnu.org/licenses/gpl-3.0.html" target="_blank"> http://www.gnu.org/licenses/gpl-3.0.html</a>
*/
function random_codes($symbols, $num_codes)
{
$length = strlen($num_codes);
$num_symbols = count($symbols);
$codes = array();
while(count($codes) < $num_codes) {
$code = '';
for($ii=0; $ii<$length; $ii++) {
$code .= $symbols[rand(0,$num_symbols-1)];
}
$codes[$code] = $code;
}
return $codes;
}
$symbols = array('2','3','4','5','6','7','9','A','C','E','F','G','H','K','M','N','P','R','T','U','W','X','Y','Z');
$codes = random_codes($symbols, 15000000);
This function generates short (7/8 chars) codes. Mostly useful for short URLs.
function generate_unique_code()
{
return base_convert(crc32(uniqid()), 10, 16);
}