PHP不重复随机数的生成方法
程序员文章站
2022-06-14 12:42:56
...
原理很简单,先写一个函数,生成0-z这36个字符中的一个。每次调用 getOptions() 方法生成一个字符,它们的存储如下:array[0] = 0, array[1] = 1, ……, array[35] = z。
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => a [11] => b [12] => c [13] => d [14] => e [15] => f [16] => g [17] => h [18] => i [19] => j [20] => k [21] => l [22] => m [23] => n [24] => o [25] => p [26] => q [27] => r [28] => s [29] => t [30] => u [31] => v [32] => w [33] => x [34] => y [35] => z )
然后在0-35之间随机生成一个数作为索引,其实就是在上面数组中随机取出一个数,作为变量 $result 中的第一个字符。这个随机索引随后会被赋值成数组最后一个,它将不会参与下一轮的随机选取。