PHP internal hash function

I am looking for PHP equivalent for JAVA

 "SomeString".hashCode();

function. The hash code I'm looking for should be the same one used for indexing Hashmaps in PHP. Hope you can help me :)

EDIT:

It's good that the function I was looking for was 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;
}
+5
source share
5 answers

Arkh github, guiguoz, , , PHP double, 2 ^ 61. java, 32- , 32- ( ), 32- .

PHP , :

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;
}

(: % v typo)

+6

php . , . Wikipedia , Java.lang.hashCode, , , php:

<?php
function getStringHashCode($string){
  $hash = 0;
  $stringLength = strlen($string);
  for($i = 0; $i < $stringLength; $i++){
    $hash = 31 * $hash + $string[$i];
  }
  return $hash;
}
+3

spl_object_hash is probably closest to what you want, but despite the name, it really doesn't return a hash of the passed value, just an internal unique identifier. I do not know if this hash was really used under the hood for arrays, etc.

+1
source

Here are my 2 cents for implementing Java hashCode in PHP:

/**
 * Simulates java hashCode function
 * hash a string to 32 bit
 * @param str the string to hash
 * @return hashed 32 bit integer
 */
function hashCode($str) {
    $str = (string)$str;
    $hash = 0;
    $len = strlen($str);
    if ($len == 0 )
        return $hash;

    for ($i = 0; $i < $len; $i++) {
        $h = $hash << 5;
        $h -= $hash;
        $h += ord($str[$i]);
        $hash = $h;
        $hash &= 0xFFFFFFFF;
    }
    return $hash;
};
+1
source

utf-8 version with emoji support

function str_hashcode($s){
    $hash = 0;
    $len = mb_strlen($s, 'UTF-8');
    if($len == 0 )
        return $hash;
    for ($i = 0; $i < $len; $i++) {
        $c = mb_substr($s, $i, 1, 'UTF-8');
        $cc = unpack('V', iconv('UTF-8', 'UCS-4LE', $c))[1];
        $hash = (($hash << 5) - $hash) + $cc;
        $hash &= $hash; // 16bit > 32bit
    }
    return $hash;
}
+1
source

All Articles