Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert numbers to an alpha numeric system with php

Tags:

php

I'm not sure what this is called, which is why I'm having trouble searching for it.

What I'm looking to do is to take numbers and convert them to some alphanumeric base so that the number, say 5000, wouldn't read as '5000' but as 'G4u', or something like that. The idea is to save space and also not make it obvious how many records there are in a given system. I'm using php, so if there is something like this built into php even better, but even a name for this method would be helpful at this point.

Again, sorry for not being able to be more clear, I'm just not sure what this is called.

like image 273
mrpatg Avatar asked Dec 09 '22 15:12

mrpatg


2 Answers

You want to change the base of the number to something other than base 10 (I think you want base 36 as it uses the entire alphabet and numbers 0 - 9).

The inbuilt base_convert function may help, although it does have the limitation it can only convert between bases 2 and 36

$number = '5000';
echo base_convert($number, 10, 36); //3uw
like image 182
Yacoby Avatar answered Dec 12 '22 03:12

Yacoby


Funnily enough, I asked the exact opposite question yesterday.

The first thing that comes to mind is converting your decimal number into hexadecimal. 5000 would turn into 1388, 10000 into 2710. Will save a few bytes here and there.

You could also use a higher base that utilizes the full alphabet (0-Z instead of 0-F) or even the full 256 ASCII characters. As @Yacoby points out, you can use base_convert() for that.

As I said in the comment, keep in mind that this is not an efficient way to mask IDs. If you have a security problem when people can guess the next or previous ID to a record, this is very poor protection.

like image 30
Pekka Avatar answered Dec 12 '22 03:12

Pekka