<?php
function generateRandomString($length = 10, $alpha = false, $numeric = false) {
if ($alpha) { $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; }
if ($numeric) { $characters = '0123456789'; }
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; ++$i) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
if (substr($randomString, 0, 1) != 2) { // if doesn't start with 2
generateRandomString($length, $alpha, $numeric); // try again
}
else {
return $randomString;
}
}
$num = generateRandomString(8, false, true);
echo ($num);
我需要它返回一个以2
开头的值,但它根本不返回任何内容,也没有错误。我在这里做错了什么?
答案 0 :(得分:3)
使用return here,更改此
if (substr($randomString, 0, 1) != 2) { // if doesn't start with 2
generateRandomString($length, $alpha, $numeric); // try again
}
到
if (substr($randomString, 0, 1) != 2) { // if doesn't start with 2
return generateRandomString($length, $alpha, $numeric); // try again
}