php产生随机数的两种方法实例代码 输出随机IP
时间:2020-10-20 13:17:01|栏目:PHP代码|点击: 次
分享下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.jb51.net foreach($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代码
本文地址:http://www.codeinn.net/misctech/13898.html