user982911 user982911 - 1 year ago 148
PHP Question

PHP internal hashCode Function

I am looking for the PHP equelent to JAVA's


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 :)


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;

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download