How to get random number in php program or script

random

To get a random number using PHP function

rand() function generates the random number

Here is the code to print the random numbers from 1 t0 19 using array

<?php
$arr = array(1, 20, NULL);

for ($i = 1; $i <20 ;$i += 1) {
$arr[$i] = rand(1, 20);
}

for ($i = 1; $i <20; $i += 1) {
echo $arr[$i];
echo “<br/>”;
}
?>

mt_rand() is also used to generate a random numbers. But its 4 times faster than the rand() function.

<?php

echo(mt_rand() . “<br>”);
echo(mt_rand() . “<br>”);
echo(mt_rand(20,100));
echo “<br/>”;

?>

array_rand() is used to returns a random key from an array or if you specify the function to return more than a key, then it returns the array of random keys.

synatx: array_rand(array, number);

Note: parameter ‘number’ is optional.

<?php
$a=array(“apple”,”banana”,”orange”,”pineapple”,”grapes”,”pomegranate”);
$random_keys=array_rand($a,3);
echo $a[$random_keys[0]].”<br>”;
echo $a[$random_keys[1]].”<br>”;
echo $a[$random_keys[2]];
?>

getrandmax() is used to return the largest possible random number

<?php

echo (getrandmax());

?>

srand() is used to seed the number generator

syntax: srand(seed);

Note: seed is an optional parameter

<?php

srand(mktime());

echo (rand());

?>