WordPress at a glance

wp_rand() WP 2.6.2

Generates a random number between the specified min and max.

Это pluggable функция — т.е. её можно заменить из плагина. Это значит, что она будет работать (подключается) только после подключения всех плагинов, а до этого момента функция еще не определена... Поэтому нельзя вызывать эту и зависящие от неё функции прямо из кода плагина. Их нужно вызывать через хук plugins_loaded или позднее, например хук init.

Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.

Is the basis for: wp_generate_password()
✈ 1 time = 0.000032s = very fast | 50000 times = 0.09s = speed of light | PHP 7.0.8, WP 4.6.1

No Hooks.

Return

Int. A random number between min and max

Usage

wp_rand( $min, $max );
$min(int)
Lower limit for the generated number
Default: 0
$max(int)
Upper limit for the generated number
Default: 0

Examples

#1 Basic usage

echo wp_rand( 99, 99999 ); // 19899, 85724, 77130, 51575
echo wp_rand( 1.5, 5.5 );  // 5, 1, 3, 4
echo wp_rand( 5, 4 );      // always 5

Notes

  • Global. String. $rnd_value
  • Static. String. $seed
  • Static. true/false. $use_random_int_functionality

Changelog

Since 2.6.2 Introduced.
Since 4.4.0 Uses PHP7 random_int() or the random_compat library if available.

Code of wp rand: wp-includes/pluggable.php WP 5.2.2

<?php
function wp_rand( $min = 0, $max = 0 ) {
	global $rnd_value;

	// Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
	$max_random_number = 3000000000 === 2147483647 ? (float) '4294967295' : 4294967295; // 4294967295 = 0xffffffff

	// We only handle Ints, floats are truncated to their integer value.
	$min = (int) $min;
	$max = (int) $max;

	// Use PHP's CSPRNG, or a compatible method
	static $use_random_int_functionality = true;
	if ( $use_random_int_functionality ) {
		try {
			$_max = ( 0 != $max ) ? $max : $max_random_number;
			// wp_rand() can accept arguments in either order, PHP cannot.
			$_max = max( $min, $_max );
			$_min = min( $min, $_max );
			$val  = random_int( $_min, $_max );
			if ( false !== $val ) {
				return absint( $val );
			} else {
				$use_random_int_functionality = false;
			}
		} catch ( Error $e ) {
			$use_random_int_functionality = false;
		} catch ( Exception $e ) {
			$use_random_int_functionality = false;
		}
	}

	// Reset $rnd_value after 14 uses
	// 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
	if ( strlen( $rnd_value ) < 8 ) {
		if ( defined( 'WP_SETUP_CONFIG' ) ) {
			static $seed = '';
		} else {
			$seed = get_transient( 'random_seed' );
		}
		$rnd_value  = md5( uniqid( microtime() . mt_rand(), true ) . $seed );
		$rnd_value .= sha1( $rnd_value );
		$rnd_value .= sha1( $rnd_value . $seed );
		$seed       = md5( $seed . $rnd_value );
		if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
			set_transient( 'random_seed', $seed );
		}
	}

	// Take the first 8 digits for our value
	$value = substr( $rnd_value, 0, 8 );

	// Strip the first eight, leaving the remainder for the next call to wp_rand().
	$rnd_value = substr( $rnd_value, 8 );

	$value = abs( hexdec( $value ) );

	// Reduce the value to be within the min - max range
	if ( $max != 0 ) {
		$value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
	}

	return abs( intval( $value ) );
}

Related Functions

From tag: PHP analogues (PHP functions replacement)

More from category: Helper Functions

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register