I am looking for the PHP equelent to JAVA's
"SomeString".hashCode();
function. The hashCode i am looking for should be the same which is used for indexing Hashmaps in PHP. I Hope you can help me :)
EDIT:
Okay found the function i was searching for its written in C and is not available in PHP itself but thanks for your help !
ulong zend_inline_hash_func(char *arKey, uint nKeyLength)
{
ulong $h = 5381;
char *arEnd = arKey + nKeyLength;
while (arKey < arEnd) {
$h += ($h << 5);
$h += (ulong) *arKey++;
}
return $h;
}
Arkh and the github solution referenced by guiguoz are in the right direction, but both fail to take into account that PHP will upconvert the integer hash value to a double as soon as it exceeds 2^61. The java function, which is calculated using fixed hardware 32-bit signed values, involves 32-bit arithmetic overflow (intrinsic to the CPU) to keep the value as a 32-bit signed integer.
In PHP, you will need to manually perform that arithmetic overflow each time the $hash is updated:
function overflow32($v)
{
$v = $v % 4294967296;
if ($v > 2147483647) return $v - 4294967296;
elseif ($v < -2147483648) return $v + 4294967296;
else return $v;
}
function hashCode( $s )
{
$h = 0;
$len = strlen($s);
for($i = 0; $i < $len; $i++)
{
$h = overflow32(31 * $h + ord($s[$i]));
}
return $h;
}
(edit: corrected %v typo)
There is no such method available in php. So you will have to implement the correct method. Wikipedia gives the algorithm used by Java.lang.hashCode which is used by strings I think, so here is a quick php version of it:
<?php
function getStringHashCode($string){
$hash = 0;
$stringLength = strlen($string);
for($i = 0; $i < $stringLength; $i++){
$hash = 31 * $hash + $string[$i];
}
return $hash;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With