Posted
Comments 0

Random values could be generated using simple PHP function as follows:

<?php
//generate 10 random values
for ($i=0; $i<10; $i++) {
  echo rand()." ";
}
//the output might be: 
//591004376 1922726400 707854443 
//951539647 123211066 452202029 
//1229956111 1102301159 1659840919 
//1686837145 

The rand() function itself will return integer value randomly between 0 to a specific value depended on its machine and defined by getrandmax() function. But if you might want limiting the result to, for example, to generate figure between 1 and 6, the script could be altered like this:

<?php
//generate 10 random numbers
for ($i=0; $i<10; $i++) {
  echo rand(1, 6)." ";
}
//the output might be
//3 5 2 1 4 2 4 1 3 4 

Could we regenerate similar set of random number values? Yes, of course. Put srand() function before generating rand().

<?php
//supply seed number
srand(1234);
//generate 10 random numbers
for ($i=0; $i<10; $i++) {
  echo rand(1, 6)." ";
}

By repeating execution of script above, the system should give similar result set. But changing seed number 1234 into another, the result set should be different..

Author
Categories PHP
Comments