|
分享下php生成隨機數的三種方法,生成1-10之間的不重復隨機數,php生成不重復隨機數的例子,需要的朋友參考下。
如何用php生成1-10之間的不重復隨機數?
例1,使用shuffle函數生成隨機數。
<?php$arr=range(1,10);shuffle($arr);foreach($arr as $values){ echo $values." ";}?>
例2,使用array_unique函數生成隨機數。
<?php$arr=array();while(count($arr)<10){ $arr[]=rand(1,10); $arr=array_unique($arr);}echo implode(" ",$arr);?>
例3,使用array_flip函數生成隨機數,可以去掉重復值。
<?php$arr=array();$count1=0;$count = 0;$return = array();while ($count < 10) { $return[] = mt_rand(1, 10); $return = array_flip(array_flip($return)); $count = count($return); } //www.jbxue.comforeach($return as $value) { echo $value." "; }echo "<br/>";$arr=array_values($return);// 獲得數組的值 foreach($arr as $key)echo $key." ";?>
本人是ASP程序員,這是首次寫php程序,一點心得發上來共享
<?php $ip2id= round(rand(600000, 2550000) / 10000); //第一種方法,直接生成 $ip3id= round(rand(600000, 2550000) / 10000); $ip4id= round(rand(600000, 2550000) / 10000); //下面是第二種方法,在以下數據中隨機抽取 $arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","60","66","218","218","62","63","64","66","66","122","211"); $randarr= mt_rand(0,count($arr_1)-1); $ip1id = $arr_1[$randarr]; echo $ip1id; echo "."; echo $ip2id; echo "."; echo $ip3id; echo "."; echo $ip4id; ?>
例輸出結果為 218.28.131.182
這個程序的特點是,生成的ip第一個字段時在指定范圍內的,設定的幾個是國內常見號段,也就是說生成的ip地址大部分是國內的
核心代碼:
<?php $arr_1 = array("http://66.249.89.99","http://66.249.89.104","http://74.125.71.105"); $randarr= mt_rand(0,count($arr_1)-1); $gip= $arr_1[$randarr]; echo $gip."$randarr"; ?>
php技術:php產生隨機數的兩種方法實例代碼 輸出隨機IP,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。