rand in php – Generate a random number in PHP

rand in php : Using the PHP Rand() Functions to Generate Random Numbers. also The rand() function is used in PHP to generate a random integer. Use of random_int(), Use of rand() function without argument, Use of rand() function with arguments, Php Random Float and Use of rand () function with bitwise operator.

The basic syntax of rand() function is following: rand in php

rand();  
or  
rand(min,max); 

rand in php
rand in php

How to Generate random numbers by PHP RAND function?

Generate random numbers:

<?php
echo(rand() . "<br>");
echo(rand() . "<br>");
echo(rand(1,50));
?>

rand in php

Parameter Description Required/Optional
min Specifies the lowest number to returned. Optional
max Specifies the highest number to be returned. Optional
Also Read This πŸ‘‰   PHP Secure Session Management System

The example of rand without parameters

<?php
 
echo "The random number without parameters: " .(rand());
 
?>

Don’t Miss : PHP Strong Random Number And String Generator

generate 2 digit unique random number in php

echo(rand(10,99) . "<br>");

generate 4 digit unique random number in php

echo(rand(1000,9999) . "<br>");

generate 4 digit unique random number in php

echo(rand(100000,999999) . "<br>");

generate 8 digit unique random number in php

echo(rand(10000000,99999999) . "<br>");

Different uses of rand () function

<?php

echo "<p> first : ". rand(). "</p>";
echo "<p> second : ". rand(). "</p>";


echo "<p> range [10-100]: ". rand(10,100). "</p>";
echo "<p>range [100-500]: ". rand(100,500). "</p>";


echo "using bitwise operator (&) with 10: ";
echo rand()&10 ;
echo "<br />using bitwise operator (&) with 50: ";
echo rand()&50 ;
?>

rand () Function in PHP

Let’s see how to generates a 4 digit number.

<?php
$random_number=rand(1000, 9999);
echo $random_number;
?>

Random number of different length

Free Live Chat for Any Issue

<?Php
$no_of_digits=7;
$var='';
for($i=1; $i<=$no_of_digits; $i++){
	$var .=rand(0,9);
}
echo "<br>Random Value = $var"; 
?>

I hope you get an idea about rand in php.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Rate this post