Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to a unique INTEGER in php

Tags:

php

how can i convert a string(i.e. email address) to unique integers, to use them as an ID.

like image 229
jspeshu Avatar asked Oct 07 '10 10:10

jspeshu


2 Answers

The amount of information a PHP integer may store is limited. The amount of information you can store in a string is not (at least if the string isn't unreasonably long.)

Thus you would need to compress your arbitrary-length string to an non-arbitrary-length integer. This is impossible without data loss.

You may use a hashing algorithm, but hashing algorithms may always have collisions. Especially if you want to hash a string to an integer the collision probability is pretty high - integers can store only very little data.

Thus you shall either stick with the email or use an auto incrementing integer field.

like image 69
NikiC Avatar answered Oct 17 '22 08:10

NikiC


Try the binhex function

from the above site:

<?php
$str = "Hello world!";
echo bin2hex($str) . "<br />";
echo pack("H*",bin2hex($str)) . "<br />";
?>

outputs

48656c6c6f20776f726c6421
Hello world!
like image 40
Preet Sangha Avatar answered Oct 17 '22 07:10

Preet Sangha