View Single Post
Old 02-25-2008, 03:27 PM   #4 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

I've just wrote us a nice function which generates identifiers just like YouTube ! Not just limited to the hexadecimal range of 0 to F.

php Code:
function getIdentifier($iLength, $bUseUpper = true, $bUseLower = true, $bUseNumber = true)
{
    $szId = '';
    $aChars = array();
   
    if($bUseUpper)  $aChars[] = range(65, 90);
    if($bUseLower)  $aChars[] = range(97, 122);
    if($bUseNumber) $aChars[] = range(48, 57);
   
    $iCount = count($aChars);
   
    if($iCount == 0)
    {
        return null;
    }
   
    for($iIndex = 0; $iIndex < $iLength; $iIndex++)
    {
        $iChannel = rand(0, $iCount - 1);
        $szId .= chr($aChars[$iChannel][rand(0, count($aChars[$iChannel]) - 1)]);
    }
   
    return $szId;
}

echo 'ID = ' . getIdentifier(6);

You can even specify which types to include using the 3 arguments after the identifier length. All of which are set to true by default. You'll of course want to add your own checker to see if the returned identifier is unique. I recommend sticking in a do while loop for that -- outside of the function itself.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
The Following 2 Users Say Thank You to Wildhoney For This Useful Post:
Alan @ CIT (02-26-2008), webosb (02-25-2008)