Assign a number (between 1 and 9) to a md5 hash
Having a md5 hash like:
md5("test") = "098f6bcd4621d373cade4e832627b4f6"
How can I write a function to return a number between 1 and 9 every time I pass the md5 hash to it? The number must always be the same, i.e. myfunc("098f6bcd4621d373cade4e832627b4f6") should always return the same numbe开发者_开发问答r. Thanks for your help.
This is WAY overkill, and the suggestion of returning left-most digit is the best...
function myfunc($md5) {
$total = 0;
foreach (str_split($md5) as $char) $total += ord($char);
return $total % 9 + 1;
}
echo myfunc("098f6bcd4621d373cade4e832627b4f6");
This way you can easily change the range of return values you are interested in by modifying the return statment.
Or, a more compact version:
function myfunc2($md5) {
return array_sum(array_map("ord", str_split($md5))) % 9 + 1;
}
You could even pass the min and max as args:
function myfunc2($md5, $min = 1, $max = 9) {
return array_sum(array_map("ord", str_split($md5))) % $max + $min;
}
myfunc2("098f6bcd4621d373cade4e832627b4f6", 10, 20);
Simplest way: find first number in md5 and return it :) You can do it with easy regexp. Of course remember to have some safe return value if no number was found (but it will happen hardly ever).
Return 1 all the time. Meets the spec!
More seriously, what do you need this number to represent?
Return the leftmost digit (in 1..9 of course) in the hash considered as a string.
Or have I missed the point ?
You essentially want a hash function of your hash function. This would be some psedo code:
int hashhash(string hash)
return (hash[0] % 9) + 1;
Here's a solution:
return substr(base_convert($md5, 16, 9), -1) + 1;
This is what you probably want although you did not say it.
精彩评论