Unique ID of a string (numeric hash)
Sometimes you need to convert a string into a unique number — for example, to use it as an ID in a database. The functions below generate a numeric hash from a string.
This can be useful when you want a compact identifier made of digits only.
Option 1
/**
* Return a numeric hash of a specified string.
*
* @see https://stackoverflow.com/a/23679870/175071
* @author Kama (wp-kama.com)
* @version 1.1
*
* @param string $string String to be hashed.
* @param int $len Number length to be returned.
* Max is 18 (for 64 bit system) 22 (for 32 bit).
* 13 is quite enough to be unique (tested on 1 000 000 vals).
*
* @return int
*/
function num_hash( $string, $len = 13 ): int {
$hash = implode( '', unpack( 'N2', md5( $string, true ) ) );
return (int) substr( $hash, 0, $len );
}
Example:
var_dump( num_hash( 'a' ) ); // int(2140051773237) var_dump( num_hash( 'asd' ) ); // int(2014669166342) var_dump( num_hash( str_repeat( 'asd', 10 ) ) ); // int(3686969916323)
Min length Unique Testing code:
$hashes = [];
$strings = [];
for( $i = 1; $i < 1000000; $i++ ){
$str = 'some string'. $i;
$strings[] = $str;
$hashes[] = Vehicles_REST_Controller::num_hash( $str, 13 );
}
print_r( [
'Generated Hash example' => $hashes[0],
'Strings all' => count( $strings ),
'Strings uniq' => count( array_unique( $strings ) ),
'Hash uniq' => count( array_unique( $hashes ) ),
] );
Option 2
/**
* Fast 64-bit unsigned numeric hash (PHP ≥ 8.1).
*/
function num_hash( string $str, int $len = 13 ): int {
$h = unpack( 'J', hash( 'xxh3', $str, true ) )[1] & 0x7fffffffffffffff;
return (int) substr( (string) $h, 0, $len );
}
Example:
var_dump( num_hash( 'a' ) ); // int(7405662395035) var_dump( num_hash( 'asd' ) ); // int(3120540762862) var_dump( num_hash( str_repeat( 'asd', 10 ) ) ); // int(6755367067389)
Conclusion
These functions provide a simple and efficient way to generate a unique numeric ID from any string. This is especially useful when working with database IDs, file naming, indexing, or any case where you need a number instead of a string. Whether you're looking to generate a numeric string hash, convert a string to number in PHP, or create a PHP string-to-int hash, these methods offer reliable solutions. They're perfect for anyone needing a unique numeric ID from a string, or trying to generate a PHP hash with digits only. If you're searching for how to turn a string into a numeric ID, generate a number from a string, or create a PHP int from a string — this approach has you covered.