Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to 5 digit string [closed]

I want to convert a number to a 5 character string. The string characters are a-z, A-Z and 0-9. Each combination of that code increments by "1"

I am not sure how to explain it, so I am going to give you an example. For example

1 = aaaaa
26 = aaaaz
27 = aaaaA
52 = aaaaZ
53 = aaaa0
62 = aaaa9
63 = aaaba
89 = aaabz
90 = aaab0

So if I had number 1035, is there a way PHP can calculate the code for that?

Sorry my question is a little vague.

The reason I want to do this is because I don't want to to show my database primary key id, I want to show this base63 format.

like image 420
Peter Stuart Avatar asked Sep 27 '13 17:09

Peter Stuart


2 Answers

I guess you could do something like this:

function custom_base_62($n)
{
    if ($n < 1)
        trigger_error('custom_base_62(): This silly system cannot represent zero.', E_USER_ERROR);

    $n -= 1;
    $symbols = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
    $r = '';

    while ($n)
    {
        $r = $symbols[$n % 62] . $r;
        $n = floor($n / 62);
    }

    return str_pad($r, 5, $symbols[0], STR_PAD_LEFT);
}
like image 147
Havenard Avatar answered Oct 01 '22 08:10

Havenard


Here is an idea you can play with, not fully sure i understand your exact goal..

<?php

function Digit_to_char($s){

  $s1 = str_split($s);
  while(list($k,$v) = each($s1)){
    $s2[] = str_replace(range(0,9), array("a","b","c","d","e","f","g","h","y","z"), $v);
  }

  return implode('',$s2);
}


echo Digit_to_char(12345); // prints bcdef

?>
like image 43
Tom Avatar answered Oct 01 '22 07:10

Tom