php隨機數不重複產生的五種方式

來源:互聯網
上載者:User
在前一篇文章中我介紹了php隨機數的產生方法,我們都知道php隨機數不管是在開發中,還是在行動裝置 App中,都是不可少的一部分,平時日常開發中經常會跟php隨機數打交道,那麼今天就給大家介紹php隨機數不重複產生的五種方式!

第一種方式:

<?php $numbers = range (1,50); //shuffle 將數組順序隨即打亂 shuffle ($numbers); //array_slice 取該數組中的某一段 $num=6; $result = array_slice($numbers,0,$num); print_r($result); ?>

第二種方式

<?php $numbers = range (1,20); //播下隨機數發生器種子,可有可無,測試後對結果沒有影響srand ((float)microtime()*1000000); shuffle ($numbers); //跳過list第一個值(儲存的是索引)while (list(, $number) = each ($numbers)) { echo "$number "; } ?>

第三種方式

<?php function NoRand($begin=0,$end=20,$limit=5){ $rand_array=range($begin,$end); shuffle($rand_array);//調用現成的數組隨機排列函數 return array_slice($rand_array,0,$limit);//截取前$limit個 } print_r(NoRand()); ?>


上述可以在1-20之產生5個不重複的php隨機數

第四種方式

<?php $tmp=array(); while(count($tmp)<5){ $tmp[]=mt_rand(1,20); $tmp=array_unique($tmp); } print_r($tmp);?>


第五種方式

<?php $tmp = range(1,30);print_r(array_rand($tmp,10));?>

這個可能是比叫簡單的了(ps:如果在range中指定了步長,就必須注意array_rand的第二個參數是否超出$tmp的長度)。

總結:

PHP提供非常豐富的數組函數,產生php隨機數大多可以從數組這個角度出發,當然如果你有更好的方法,希望對你有所協助,本文也算是拋磚引玉了。

相關推薦:

php隨機數產生的方法


PHP隨機數


php隨機數 紅包隨機產生演算法php版

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.