faqts : Computers : Programming : Languages : PHP

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

44 of 51 people (86%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How to generate 'base' strings in PHP (base16 / base36 / base64 etc)?

Nov 28th, 2008 07:14
healthy man, dman, Shashank Tripathi,


If you wish to generate base16, base36 and base64 strings from a given 
number, you can use the following function. 
For instance, if for some reason I need to generate an alphanumeric 
sequence using a-z (26 alphabets) and 0-9 (10 numbers) which makes 
36 characters in all, then that gives me 36 ^ 3 possible values, which 
equals 46656  (i.e., 1 - 46655). A base36 translation would convert 
all numbers from 0 to 46655 into strings starting from 1 to ZZZ. E.g., 
   getBaseString(1, 36)   will return 1
   getBaseString(10, 36)   will return a
   getBaseString(100, 36)   will return 2s
   getBaseString(9000, 36)   will return 6y0
   getBaseString(46655, 36)   will return zzz
(All permutations and combinations of alphabets and numbers). 
<?
/**
 * Function to calculate base16, base36 and base64 values from a 
 * number. Very useful if you wish to generate alphanumeric sequences 
 * from numbers. 
 * 
 * @param $value The number 
 * @param $base The base to be applied (16, 36 or 64)
 * @return The calculated string 
 * @author Shashank Tripathi ([email protected])
 * @version 0.1 - Let me know if something doesnt work
 * 
 */
function getBaseString($value, $base) 
{
    $baseChars = array('0', '1', '2', '3', '4', '5',
                       '6', '7', '8', '9', 'a', 'b',
                       'c', 'd', 'e', 'f', 'g', 'h',
                       'i', 'j', 'k', 'l', 'm', 'n',
                       'o', 'p', 'q', 'r', 's', 't',
                       'u', 'v', 'w', 'x', 'y', 'z'
                     );
    $remainder = 0;
    $newval = "";
    while ( $value > 0 ) 
    {
        $remainder = $value % $base;
        $value = ( ($value - $remainder)/ $base );
        $newval .= $baseChars[$remainder];
    }
    return strrev($newval);
}
$number = 46655;
echo "The string for $number for instance, is " . getBaseString
($number, 36);
?>
http://www.healthdothealth.com
http://www.healthxhealth.com
http://www.mesotheliomainmesothelioma.com
http://www.healthfirewall.com
http://www.flathealth.com
http://www.healthbodyguard.com