簡體   English   中英

PHP隨機字符串Ascii

[英]Php random String Ascii

我是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;
}

他永遠不會陷入困境。 首先,如果我刪除了$lenghth變量並進行了硬編碼,那么循環中的數字就進入了。 但是后來我什么也沒得到。

這是因為該函數僅使用局部變量 您需要這樣做:

function getString() {
    $text="";

    $length=32;
    $startAscii=48;
    $endAscii=122;

    for($count = 1; $count < $length; $count++) {
        $text=$text.chr(mt_rand($startAscii, $endAscii));
    }

    return $text;
}

或者,您可以這樣做,但這是更“丑陋”的解決方案:

function getString() {
    global $length, $startAscii, $endAscii;

    $text="";

    for($count = 1; $count < $length; $count++) {
        $text=$text.chr(mt_rand($startAscii, $endAscii));
    }

    return $text;
}

或者,您也可以將其用作參數,我認為這是最好的解決方案,因為此功能更有效(您可以在不編輯內部代碼的情況下將此功能與其他值一起使用):

function getString($length, $startAscii, $endAscii;) { ... }

$length=32;
$startAscii=48;
$endAscii=122;

echo getString($lenght, $startAscii, $endAscii);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM