PHP how to get a random number that is different from values of an array -


example: have array 3 values:

0 = 1 1 = 4 2 = 5 

i want random number like

$random = rand(1, 5); 

but need number different array values. need return 2 or 3.

this should work you:

(here create range random number range(). rid of these numbers don't want array_diff(). , @ end can use array_rand() random key/number)

<?php      $blacklist = [1, 4, 5];     $range = range(1, 5);     $randomarray = array_diff($range, $blacklist);     echo $randomarray[array_rand($randomarray, 1)];  ?> 

output:

2 or 3 

edit:

just did benchmarks , method loop slower code above!

i created array(blacklist) 1...100'000 , random number array 1... 100'001.

so script should create one/unique random number. loop method error:

fatal error: maximum execution time of 30 seconds exceeded

and posted code above takes 1.5 sec in average.


Popular posts from this blog