PHP自學筆記21--生成數字字母隨機字符串

沒想到竟然如此簡單。

<?php
$str="0123456789abcdefghijklmnopqrstuvwxyz"; //這裏只有小寫字母,需要的話還可以自己加上大寫字母和標點符號
$n=10;   //定義隨機串的長度
$len=strlen($str);
$s="";
$iTmp=rand(0,$len-1);

#echo "len:".$len."--rand:".$iTmp."<br>";
for($i=0;$i<$n;$i++){
    $iTmp=rand(0,$len-1);
    #echo "idx:".$i."--rand:".$iTmp;
    $s=$s.$str[$iTmp];
    #echo "--s:".$s."<br/>";
}

echo $s."<br/>";
?>

運行結果:

wlcn257hj2

 

如果想要生成不重複的話,就要用到array_unique函數啦,它將除掉重複的部分。

我也測試了一個小例子。

<?php 
header("Content-Type:text/html;charset=utf-8");

function GetRandNoRepeat($num){
    $start=0;
    $end=100;//0-100
    $cnt=0;
    while($cnt<$num){
        $tmp[]=rand($start,$end);//generate random
        $a=array_unique($tmp);
        $cnt=count($a);
    }
    
    return implode(" ", $a);
}


$str=GetRandNoRepeat(20);

echo "<b>output 20 random:</b><br/><br/>";
echo "random:<b>".$str."</b><br/>";
echo "<b><br/><font color='green'>from 0 to 100 and no repeat</font><b>";

?>

運行結果:

output 20 random:

random:81 58 68 2 50 19 47 9 43 32 75 4 5 66 60 64 41 35 40 45

from 0 to 100 and no repeat

 

感興趣的朋友,請寫一個數字字母不重複的函數吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章