我正在尝试在 PHP 中创建一个随机字符串,但我绝对没有输出:
<?php function RandomString() { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randstring = ''; for ($i = 0; $i < 10; $i++) { $randstring = $characters[rand(0, strlen($characters))]; } return $randstring; } RandomString(); echo $randstring;
我究竟做错了什么?
要具体回答这个问题,有两个问题:
$randstring
这是一个带有更正的代码片段:
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; }
使用以下调用输出随机字符串:
// Echo the random string. // Optionally, you can give it a desired string length. echo generateRandomString();
**请注意,这会生成可预测的随机字符串。