为什么PHP这样选择随机值? [英] Why is PHP selecting the Random Values like that?

查看:83
本文介绍了为什么PHP这样选择随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以...我正在测试某些东西,并注意到在运行此代码时:

So... I was testing something and noticed that when I run this code:

$arr = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", 1);
print_r(implode(array_rand(array_flip($arr), 16)));

输出为

The Output is

Refresh 1: BDFIJKPTVkl12789
Refresh 2: HIJKMQWYdfmorsw3
Refresh 3: FGHMNRVYfhknouw5
Refresh 4: AFIJKRSVeiuwx579
Refresh 5: DJORYZcgijlpqry1
Refresh 6: EISWbhjmoqr45689
Refresh 7: CDEFOTXdhkloqr27
Refresh 8: AEFIKLNORSknx349
Refresh 9: DEFHJMTVZcgpstz0
Refresh 10: CLQTZbefhnpq1279

为什么每次输出都以1到5个大写字母开头?对我来说,那种随机性"似乎很奇怪.

Why does the output start everytime with 1 to 5 uppercase letters? That "randomness" seems weird to me.

我想知道为什么会得到这个结果.

I would like to know why I get this result.

推荐答案

array_rand (自PHP 5.2.10起)不再改组它生成的随机键列表(您会注意到输出字符串全部按字母顺序排列,即字符按相同顺序排列)因为它们在输入字符串中).如果您不希望这种行为,请使用 shuffle array_slice 代替:

array_rand (since PHP 5.2.10) no longer shuffles the list of random keys that it generates (you'll notice that your output strings are all in alphabetical order i.e. the characters are in the same order as they are in the input string). If you don't want that behaviour, use shuffle and array_slice instead:

$arr = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", 1);
shuffle($arr);
echo implode('', array_slice($arr, 0, 16));

输出:

dU54f9wBjZbAKgCP

在3v4l.org上进行演示

这篇关于为什么PHP这样选择随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆