PHP | mt_rand( ) Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
echo mt_rand();
  
?>

chevron_right


Output:

34567

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.