I have this function in javascript - it works correctly
// javascript function myhash(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { oneChar = str.charCodeAt(i); hash = ((hash << 5) - hash) + oneChar; hash &= hash; } return hash; }
And I'm trying to rewrite this function in PHP, but for the same input it gives a different result than the one that JS has.
// php function myhash($str) { $hash = 0; if (strlen($str) == 0) return $hash; for ($i = 0; $i < strlen($str); $i++) { $oneChar = ord($str[$i]); $hash = (($hash << 5) - $hash) + $oneChar; $hash &= $hash; } return $hash; }
Example input and output:
console.log(myhash("example")); // output: -1322970774 echo myhash("example"); // output: 93166309738
Does anyone know where there might be a problem? They look the same, but apparently it is not.
source share