I'm new at PHP and don't have any idea, why this doensn't works:
$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. 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.