non numerical string to integer

Recommended Posts

How can I convert a string into a number, but so that this number is unique for that string.So if string123 has number 1243225634123 then there is no other string that has the same number.Also, how can I add 2 numbers together in the following way:123 + 456 = 123456I do not know the lenght of each of those numbers. (else i could've done 123*1000 + 456)Thanks in advance,

Share on other sites

If you put all your strings in an array, you can use the in_array function to see if the test string already exists.PHP is loosely typed. An integer will cast itself into a string if you treat it like a string. So just use the dot operator to concatenate the values.\$a = 123;\$b = 456;echo \$a . \$b;// "123456"

Share on other sites

How can I convert a string into a number, but so that this number is unique for that string.So if string123 has number 1243225634123 then there is no other string that has the same number.
That's what a hash is, but a hash isn't going to be strictly unique, because the set of possible hashes is finite and the site of possible strings to hash is infinite. The MD5 algorithm produces a 32-character (128-bit) hash, SHA-1 produces a 40-character (160-bit) hash, then SHA-256, SHA-384, SHA-512 etc produce larger hashes that are less likely to collide with another string to produce the same hash.
Share on other sites

That's what the question meant?

Share on other sites

Note that hashes are (usually) in hexadecimal format - you can convert them to decimal if you like, though. Also, even the old MD5 algorithm produces a hash out of a possible ~340000000000000000000000000000000000000 (3.4 × 1038) - so you're very unlikely to get a collision randomly.

Share on other sites

That's what the question meant?
I'm just guessing...
3.4 × 1038
That's way off, it's 3.4028236692093846346337460743177e+38. Sheesh, you were off by like trillions and trillions.
Share on other sites

I did say "around"! But yes, I'm out by more than 2.8 undecillion.

Share on other sites

Of course, if uniqueness is very important you can work out an encoding of the string as an integer that is unique (I'm assuming that the end result is just a unique string containing only 0-9 digits?). This would be particularly simple if we specify that the encoding works on ASCII characters only because you can just loop over the string concatenating the ASCII decimal value (padded to three digits in every case), or a more direct conversion using the binary representation of each character.That would give you (for all ASCII strings) a unique encoding in just decimal digits. Though I have to wonder why you wouldn't just have the string representation - these integers are going to get huge very fast. The encoding of this paragraph as a unique integer would be enormous.A hash which doesn't enforce uniqueness would be more practical for large inputs.

Edited by AElliott