เขียน PHP ให้ random เลข แบบไม่ซ้ำ


หน้าแรก PHP MySQL เกร็ดความรู้ เขียน PHP ให้ random เลข แบบไม่ซ้ำ

อันนี้เป็น code Php เขียน function ในรูปแบบเชิงวัตถุ (Object) นะครับ เวลาใช้งานก็ให้สร้าง object ใหม่ขึ้นมาแล้วเรียกใช้ฟังก์ชั่น (function) ภายใน object นั้น (ไม่รู้ผมพูดถูกป่าว) เอาเป็นว่าดูตัวอย่างแล้วเอาไปประยุกต์ใช้ดีกว่าครับ

ฟังก์ชั่นในรูปแบบ class
class GetRandomNum {
private $sta;
private $nend;
private $numb;
private $nu_test;
private $used;
private $i;
function __construct($a,$b,$c){
$this->sta = $a;
$this->nend = $b;
$this->numb = $c;
}
function operate(){
if(($this->nend - $this->sta) >= $this->numb -1){
$this->used = array();
for ($this->i=0; $this->i < $this->numb; $this->i++){
$this->nu_test = mt_rand($this->sta,$this->nend);
while(in_array($this->nu_test,$this->used)){
$this->nu_test = mt_rand($this->sta,$this->nend);
}
$this->used[] = $this->nu_test;
}
return $this->used;
}else return false;
}
}

เวลาใช้งาน ก็ประมาณตามด้านล่าง โดย
$begin คือ เลขเริ่มต้นที่ให้แรนดอม
$end คือ เลขสุดท้ายที่ให้แรนดอม
$number คือ จำนวนของตัวเลขที่ต้องการให้ random ออกมา

ตามตัวอย่างนี้จะได้ตัวแปร $test เป็น array ที่บรรจุตัวเลข random แบบไม่ซ้ำกัน
$test = new GetRandomNum($begin,$end,$number);
$test->operate();

refer: http://www.kengcom.com/random-number-php-function/



ขึ้นไปด้านบน