Saturday, November 15, 2014

PHP Alphanumeric Encoder/Decoder

The following two functions are an alphanumeric encoder and decoder respectively.  The intent of the first function is to take a base 10 number and encode it using some character set.  It is hardcoded to use a charset of “1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ”.  Because there are 36 characters in this character set, the encoder effectively becomes a base 10 to base 36 encoder by default.  But you can either alter the default encoding string or pass in the alphabet you want to use as a second argument and encode the base 10 number to any base you desire.  The second function reverses the process.

I have tested both functions quite extensively, and they both appear to work flawlessly.

  /**
    * Encode a base 10 number into some alternate base
    *
    * @param int $num
    * @param string $alphabet
    * @return string $alphaNum
    */
   public static function alphaEncode($num, $alphabet=null) {
      $result = '';
      if (!$alphabet) {
         $alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      }
      $alphabet = str_split($alphabet);
      if ($num == 0) {
         return $alphabet[0];
      }
      $base = count($alphabet);
      while ($num > 0) {
         $remainder = $num % $base;
         $num = floor($num / $base);
         $alphaNum = $alphabet[$remainder] . $alphaNum;
      }
      return $alphaNum;
   }
   
   /**
    * Decode an encoded number back into base 10
    *
    * @param string $alphaNum
    * @param string $alphabet
    * @return int $num
    */
   public static function alphadDecode($alphaNum, $alphabet=null) {
      $result = '';
      if (!$alphabet) {
         $alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      }
      $alphabet = str_split($alphabet);
      $base = count($alphabet);
      $num = 0;
      $idx = 0;
      $charCount = strlen($alphaNum);
      $charArray = str_split($alphaNum);
      foreach ($charArray as $char) {
         $power = ($charCount - ($idx + 1));
         $charIndex = array_search($char, $alphabet);
         $num += $charIndex * pow($base, $power);
         $idx++;
      }
      return $num;

   }