There's a built-in function for converting from one base to another, base_convert(). The alphabet is fixed, but you can use strtr() to replace those digits with your own.
"The output for tenTo31(2) should be 2": One possibility is to make '2' the third symbol again.
function tenTo31($num) {
static $from = "0123456789abcdefghijklmnopqrstu";
static $to = "yz23456789abcdefghjkmnpqrstuvwx";
return strtr(base_convert($num, 10, 31), $from, $to);
}
for($i=0; $i<31; $i++) {
echo $i, '=', tenTo31($i), ' | ';
if ( 9===$i%10 ) echo "\n";
}
prints
0=y | 1=z | 2=2 | 3=3 | 4=4 | 5=5 | 6=6 | 7=7 | 8=8 | 9=9 |
10=a | 11=b | 12=c | 13=d | 14=e | 15=f | 16=g | 17=h | 18=j | 19=k |
20=m | 21=n | 22=p | 23=q | 24=r | 25=s | 26=t | 27=u | 28=v | 29=w |
30=x |
edit:
To convert the base(31) number back to decimal you first have to reverse the translation (strtr) and then call base_convert(.., 31, 10). You can combine the conversion from and to base(31) in a single function.
function convert_ten_31($num, $numIsDecimal) {
static $default = "0123456789abcdefghijklmnopqrstu";
static $symbols = "yz23456789abcdefghjkmnpqrstuvwx";
if ( $numIsDecimal ) {
return strtr(base_convert($num, 10, 31), $default, $symbols);
}
else {
return base_convert(strtr($num, $symbols, $default), 31, 10);
}
}
// testing
for($i=0; $i<10000; $i++) {
$x = convert_ten_31($i, true);
$x = convert_ten_31($x, false);
if ( $i!==(int)$x ) {
var_dump($i, $x);
die;
}
}
echo 'done.';
It's also easily possible to write a function like base_convert() yourself that take the symbols as parameter and thus having one flexible function instead of tenTo30(), tenTo31(), tenTo32(), ....