Here is a simple way in PHP to hash a string to an integer. That is, mapping a string to a specific number.
1 2 3 4 | function str_hash($str, $range=100){ $number = crc32($str); return $number % $range; } |
This function has a default range of 100. (That means the outcome can be 0 – 99 )
Example Usage
Simple load-balancing depends on the username
1 2 3 4 | $servers = array('10.0.0.1', '10.0.0.2', '10.0.0.3'); $serverIndex = str_hash($username, 3); $link = processDownload($servers[$serverIndex], $fileId); header('Location: ' . $link); |
Extend Reading
1. This stackoverflow post is related to how to hash a string to integer using md5, but I found the resulting integer is too large for my practical use
http://stackoverflow.com/questions/965304/php-hash-form-string-to-integer