PHP 8.1: MurmurHash3 hash algorithm support

TypeNew Feature

PHP 8.1 adds support for MurmurHash hashing algorithm.

MurmurHash is a non-cryptographic hashing algorithm, and PHP 8.1 supports MurmurHash3 version of it. Following variants are supported:

  • murmur3a: 32-bit hash
  • murmur3c: 128-bit hash on x86 architecture
  • murmur3f: 128-bit hash on x64 architecture
hash('murmur3a', ''); // "ac96fab7"
hash('murmur3c', ''); // "6d0fe9c3f960dc75cf42632f3e78ffda"
hash('murmur3f', ''); // "ba0189037daec822d973d304602d44f0"

MurmurHash is a streaming hash, which means the values can be updated in sequence without having to hash the input string as a whole.

$context = hash_init('murmur3f');
hash_update($context, 'php');
hash_update($context, '.');
hash_update($context, 'watch');
$hash = hash_final($context); // "ba0189037daec822d973d304602d44f0"

MurmurHash is not designed as a cryptographic hashing algorithm. For password hashing, use password_hash and its friends. Furthermore, none of the MurmurHash variants are allowed in hash_hmac function.

MurmurHash algorithm is faster than most of the hashing algorithms, and is one of the fastest non-cryptographic algorithms available in PHP, along with the new xxHash algorithms.

Algorithm PHP implementation speed (GB/s)
murmur3a 3.98
murmur3c 6.20
murmur3f 8.87
sha2-256 0.25
sha1-160 0.70
md5-128 0.77

The results above are an excerpt from PHP Hash Algorithm Benchmarks.

Custom Seed Options

PHP 8.1 supports specifying algorithm-specific options with the new $options parameter. Along with this, murmur* hashing algorithms accept additional options. The only supported option is seed value.

hash('murmur3f', ''); // "ba0189037daec822d973d304602d44f0"
hash("murmur3f", "", false, ["seed" => 42]); // 0cafc26e49efe230cdbd109458fef893
hash("murmur3f", "", options: ["seed" => 42]); // 0cafc26e49efe230cdbd109458fef893

The third example uses named parameters introduced in PHP 8.0.

Backwards Compatibility Impact

MurmurHash is newly added to PHP 8.1, and due to current lack of a hash registry that supports adding custom hashing algorithms, producing MurmurHash hashes using the hash() function is not possible on older PHP versions.

On PHP 8.0, a ValueError exception will be thrown if attempted to hash('murmur...', '...'):

Fatal error: Uncaught ValueError: hash(): Argument #1 ($algo) must be a valid hashing algorithm in ...:...

On PHP versions prior to 8.0, a warning will be raised:

Warning: hash(): Unknown hashing algorithm: murmur3a in ... on line ...

Alternatives implementations include:

Related Changes