WordPress at Your Fingertips

Unique ID of a string (string numeric hash)

Code below allow to get number only hash. For example we need to get unique numeric hash for custom string to use it as ID in Date Base. This function helps to get such a number form passing string:

/**
 * Return a numeric hash of a specified string.
 *
 * @see https://stackoverflow.com/a/23679870/175071
 *
 * Min length Unique Testing code:
 *
 * ```php
 * $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 ) ),
 * ] );
 * ```
 *
 * @param string  $string  String to be hashed.
 * @param int     $len     Number length to be returned. Maximum is 22. 13 is enough to be an unique number
 *                         (was tested on 1 000 000 strings).
 *                         Note: Max length for the 64 bit system is — 18 digits.
 * @return number
 *
 * @version 1.0
 * @author Kama (wp-kama.com)
 */
function num_hash( $string, $len = 13 ){

	$numhash = unpack( 'N2', md5( $string, true ) );

	$hash = $numhash[1] . $numhash[2];

	if( $len )
		$hash = substr( $hash, 0, $len );

	return (int) $hash;
}
1 comment
    Log In