I want to create a random number using rand() Where the number != to ( 516 for instance )
for instance if I have number "5" in the database and I want to insert a random number != 5.
I want to create a random number using rand() Where the number != to ( 516 for instance )
for instance if I have number "5" in the database and I want to insert a random number != 5.
One solution...
$disallow = 5;
$random_value = $disallow;
while($random_value == $disallow) {
$random_value = rand();
}
echo $random_value;
Documentation on rand, http://php.net/manual/en/function.rand.php.
this one will exclude all values given in an array.
$excluded_nums = array( .... );
$val = null;
do {
$val = rand();
} while (in_array($val, $excluded_nums));
but you may be interested in exploring another method, perhaps openssl_random_pseudo_bytes
I am creating a secure login system based on cookies, so the number has to be unpredictable.
Instead of generating numbers, it's recommended to generate an opaque identifier such as UUID v4 that's meant to be unpredictable (provided a proper entropy source is used); an example identifier:
de305d54-75b4-431b-adb2-eb6b9e546014
I've created a function to generate this identifier in an earlier answer.
I have a list of numbers in the database and I want to generate a number != to all of them
The approach I would recommend is to add a UNIQUE constraint on the identifier and write a loop that generates a new identifier and attempts to insert it; it ends when the insertion doesn't cause a constraint error; to put the odds in perspective, you're more likely to get hit by a meteorite than hitting a duplicate value.
Use arrays and rand:
$ran_begin = array(1,2,3,4,6,7,8,9);//not contain 5 and 0
$ran = array(0,1,2,3,4,5,6,7,8,9);
$random_value = '';
$k = array_rand($ran_begin);
$v = $array[$k];
$random_value = $random_value.$v;
$k = array_rand($ran);
$v = $array[$k];
$random_value = $random_value.$v;
$k = array_rand($ran);
$v = $array[$k];
$random_value = $random_value.$v;
..............................