[英]Php random String Ascii
I'm new at PHP and don't have any idea, why this doensn't works: 我是PHP新手,不知道为什么不起作用:
$lenght=32;
$startAscii=48;
$endAscii=122;
echo getString();
function getString() {
$text="";
for($count = 1; $count < $lenght; $count++) {
$text=$text.chr(mt_rand($startAscii, $endAscii));
}
return $text;
}
He goes never into for loop. 他永远不会陷入困境。 First, if I remove the
$lenghth
variable and hard code the number in the loop he goes inside. 首先,如果我删除了
$lenghth
变量并进行了硬编码,那么循环中的数字就进入了。 But then I don't get anything out of it. 但是后来我什么也没得到。
It is because the function is using only local variables . 这是因为该函数仅使用局部变量 。 You need do this:
您需要这样做:
function getString() {
$text="";
$length=32;
$startAscii=48;
$endAscii=122;
for($count = 1; $count < $length; $count++) {
$text=$text.chr(mt_rand($startAscii, $endAscii));
}
return $text;
}
Or you can do that, but this is more "uglier" solution: 或者,您可以这样做,但这是更“丑陋”的解决方案:
function getString() {
global $length, $startAscii, $endAscii;
$text="";
for($count = 1; $count < $length; $count++) {
$text=$text.chr(mt_rand($startAscii, $endAscii));
}
return $text;
}
Or you can do it as parameters, which I think is best solution, because this function is more effective (you can use this function with different values without editing code inside): 或者,您也可以将其用作参数,我认为这是最好的解决方案,因为此功能更有效(您可以在不编辑内部代码的情况下将此功能与其他值一起使用):
function getString($length, $startAscii, $endAscii;) { ... }
$length=32;
$startAscii=48;
$endAscii=122;
echo getString($lenght, $startAscii, $endAscii);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.