Skip to content
Related Articles

Related Articles

PHP | mt_rand( ) Function
  • Last Updated : 07 Mar, 2018

While working with algorithms we often come across situations when we need to generate random integers. The most common way to generate random numbers is using Mersenne Twister.
The Mersenne Twister is a pseudorandom number generator which got its name derived from the fact that its period length is chosen to be a Mersenne prime. It was the first pseudorandom number generator to provide fast generation of high-quality pseudorandom integers. It was designed specifically to rectify most of the flaws found in older pseudorandom number generators.
So in PHP, there is an inbuilt function mt_rand() which is based on Mersenne Twister which helps in generating random numbers.

The mt_rand() function generates a random integer between the specified minimum and maximum values. It produces a better random value and is faster than the rand() function. You may also refer to the article on PHP | rand() Function which is another inbuilt function in PHP to generate random numbers.

Syntax:

int mt_rand($min, $max)

Parameters: This function accepts two parameter which are described below:

  1. $min : It is an optional parameter. It specifies the lowest number to be returned.The default value is 0.
  2. $max : It is an optional parameter. It specifies the highest number to be returned.

Return Value: It returns a random number between min (or 0) and max and the return type is integer.



Examples:

Input : mt_rand()
Output : 34567

Input : mt_rand(15, 50)
Output : 49

Below programs illustrate the working of mt_rand() in PHP:

Program 1:




<?php
  
echo mt_rand();
  
?>

Output:

34567

Program 2:




<?php
  
echo mt_rand(15, 50);
  
?>

Output:

49

Important points to note :

  • mt_rand() function generates a random integer using the Mersenne Twister algorithm.
  • It produces a better random value and is faster than the rand() function.

Reference:
http://php.net/manual/en/function.mt-rand.php

My Personal Notes arrow_drop_up
Recommended Articles
Page :