Skip to content

Instantly share code, notes, and snippets.

@aalfiann
Last active April 13, 2018 11:43
Show Gist options
  • Save aalfiann/4deb1dcd2121005a704786d4d7885f90 to your computer and use it in GitHub Desktop.
Save aalfiann/4deb1dcd2121005a704786d4d7885f90 to your computer and use it in GitHub Desktop.
Generate Unique Numeric ID in PHP
/**
* Generate Unique Numeric ID in PHP
* Note:
* - In 32bit, if set $abs to true will make lengths of digits fixed to 10, but will reduce the level of uniqueness
* - In 32bit, if set $abs to false sometimes will return 11 digits because of negative number.
* - This is based of function uniqid() which uniqueness is still not guaranteed as mentioned in http://php.net/manual/en/function.uniqid.php
*
* @param prefix = adding additional value on the first to get more uniqueness level.
* @param suffix = adding additional value on the last to get more uniqueness level.
* @param fixedkey = adding additional value on uniqid string before converted to numeric
* @param abs = Will make sure all return value is positive and fixed length 10 (without any prefix or suffix). Default is true.
*
* @return string
*/
function uniqidNumeric($prefix,$suffix,$fixedkey,$abs=true){
$data = (($abs)?abs(crc32(uniqid($fixedkey))):crc32(uniqid($fixedkey)));
$pad = (10 - strlen($data));
if($pad > 0){
$leading = "";
for ($i=1;$i<=$pad;$i++){
$leading .= '0';
}
return $prefix.str_replace('-','00',str_pad($data, 10, $leading, STR_PAD_LEFT)).$suffix;
}
return $prefix.str_replace('-','0',$data).$suffix;
}
// Test loop 100 times uniqid numeric in a single thread
echo '<br> Generate only numeric<br>';
for ($i=1;$i<=100;$i++){
echo $i.' : '.uniqidNumeric().'<br>';
}echo '<br>';
echo '<br> Generate with prefix<br>';
for ($i=1;$i<=100;$i++){
echo $i.' : '.uniqidNumeric('PREFIX').'<br>';
}echo '<br>';
echo '<br> Generate with prefix and suffix<br>';
for ($i=1;$i<=100;$i++){
echo $i.' : '.uniqidNumeric('PREFIX','SUFFIX').'<br>';
}echo '<br>';
echo '<br> Generate with prefix, suffix and fixed key<br>';
for ($i=1;$i<=100;$i++){
echo $i.' : '.uniqidNumeric('PREFIX','SUFFIX','yourfixedkey').'<br>';
}echo '<br>';
echo '<br> Generate with prefix, suffix, fixed key, non abs<br>';
for ($i=1;$i<=100;$i++){
echo $i.' : '.uniqidNumeric('PREFIX','SUFFIX','yourfixedkey',false).'<br>';
}echo '<br>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment