PHP如何获得的随机数不同于阵列的值 [英] PHP how to get a random number that is different from values of an array
问题描述
例如:
我有3个值的数组:
Example: I have an array with 3 values:
0 = 1
1 = 4
2 = 5
我想获得像
$random = rand(1, 5);
但我需要得到一个数字,它是从数组的值不同。我需要它返回2或3。
But I need to get a number that is different from the array values. I need it to return 2 or 3.
推荐答案
这应该为你工作:
(在这里,我创建你在何处获得的随机数与 <$ C $的范围C>范围() 。然后,我摆脱这些数字,你不的 和array_diff()
,并在结束时,你可以简单地使用的 array_rand()
得到一个随机密钥/数)
(Here I create the range from where you get your random number with range()
. Then I get rid of these numbers which you don't want with array_diff()
. And at the end you can simply use array_rand()
to get a random key/number)
<?php
$blacklist = [1, 4, 5];
$range = range(1, 5);
$randomArray = array_diff($range, $blacklist);
echo $randomArray[array_rand($randomArray, 1)];
?>
输出:
2 or 3
编辑:
只是做了一些基准和与循环中的方法比code以上!
Just did some benchmarks and the method with the loop is much slower than the code above!
我创建从1 ... 100000数组(黑名单)和1的随机数序列... 100'001。
I created an array(blacklist) from 1...100'000 and a random number array from 1... 100'001.
这样的脚本应该只创建一个/唯一的随机数。随着循环方法,你得到一个错误:
So that script should only create one/unique random number. With the loop method you get an error:
致命错误:超过30秒的最长执行时间
Fatal error: Maximum execution time of 30 seconds exceeded
和与贴code上面需要1.5秒,平均。
And with the posted code above it takes 1.5 sec in average.
这篇关于PHP如何获得的随机数不同于阵列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!