★ wanayoo — archive 1999 http://fr.php.net/manual/hu/function.rand.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<rad2deground>
view the version of this page
Last updated: Fri, 18 Feb 2005

rand

(PHP 3, PHP 4 , PHP 5)

rand -- véletlenszámot generál

Leírás

int rand ( void )

int rand ( [int min, int max] )

Ha a min és max paraméterek nélkül hívod meg az mt_rand() függvényt, akkor az ál véletlenszám értéke 0 és RAND_MAX közé fog esni. Ha pl. 5 és 15 közé (bezárólag) eső véletlen számot akarsz kapni, akkor mt_rand(5, 15) kell írni.

Régebbi PHP verziókban a véletlenszám-generátor kiinduló értékét a srand() függvénnyel kell beállítani, de a 4.2.0-tól ez már nem szükséges.

Megjegyzés: A 3.0.7 verziók előtt a max paraméter helyett range (tartomány) szerepelt. Ezekben a verziókban az előző példával egyenértékű megoldás a mt_rand (5, 11), hogy 5 és 15 közé eső véletlen számot kapj.

Lásd még: srand(), getrandmax() és mt_rand()!



add a note add a note User Contributed Notes
rand
phpdeveloper AT o2 DOT pl
15-Feb-2005 04:29
This is most simple random array generator, hope zo ;-)
Moreover it uses some PHP array features :-), and does not search through array haystack, just checks for data if its set :P.

<?php

function GetRandomArray($min,$max,$num) {
  
  
#data check
  
$range = 1 + $max + $min;
   if (
$num > $range) return false;
   if (
$num < 1) return false;
  
  
#data prep
  
$result = array();
  
$a = rand($min,$max);
  
$result[$a] = $a;
  
  
#loop me baby ;-)
  
while(count($result) < $num) {
       do {
$a = rand($min,$max); } while(isset($result[$a]));
      
$result[$a] = $a;
   }
  
   return
$result;
}

var_dump(GetRandomArray(3,10,5));
?>

nice coding 4 U all :-)
[k3oGH]
12-Feb-2005 07:34
<?php
//A way to make random quotes.
$file="quotefile.txt";
$file=file($file);
$count=count($file);
$i=0;

$rand=rand($i, $count);
echo
$rand;

//this will output a random line in a textfile called quotefile.txt
?>
php dot net at dannysauer dot com
09-Feb-2005 03:47
Actually, if you want 2 different random numbers, you should probably use a while loop.  This is quicker and doesn't have the possibility of running into a recursive function limit.

<?php
function fn_arrRandom($min, $max){
  
// generate two random numbers
  
$iRandom1 =0;
  
$iRandom2 = 0;
  
// compare them
  
while ($iRandom1 == $iRandom2){
      
// the numbers are equal, try again
      
$iRandom1 = rand($min, $max);
      
$iRandom2 = rand($min, $max);
   }
  
// they're not equal - go ahead and return them
  
return array($iRandom1, $iRandom2);
}

print_r(fn_arrRandom(3, 13));
?>

At that point, we may as well write a function that returns an arbitrary number of differing random numbers:

<?php
function random_array($min, $max, $num){
  
$range = 1+$min-$max;
  
// if num is bigger than the potential range, barf.
   // note that this will likely get a little slow as $num
   // approaches $range, esp. for large values of $num and $range
  
if($num > $range){
     return
false;
   }
  
// set up a place to hold the return value
  
$ret = Array();
  
// fill the array
  
while(count($ret)) < $num){
    
$a = false; // just declare it outside of the do-while scope
     // generate a number that's not already in the array
     // (use do-while so the rand() happens at least once)
    
do{
        
$a = rand($min, $max);
     }while(
in_array($ret, $a));
    
// stick the new number at the end of the array
    
$ret[] = $a;
   }
   return
$ret;
}

print_r(random_array(3, 13, 5));
?>
tech_niek at users dot sourceforge dot net
08-Feb-2005 09:50
If you want to generate two +different+ random numbers in the same range:
<?
function fn_arrRandom($min, $max){

  
// generate two random numbers
  
$iRandom1 = rand($min, $max);
  
$iRandom2 = rand($min, $max);
  
  
// compare them
  
if ($iRandom1 !== $iRandom2){
      
// the numbers are different, great
  
} else {
      
// the numbers are equal, try again
      
return fn_arrRandom($min, $max);
   }
   return array(
$iRandom1, $iRandom2);
}

print_r(fn_arrRandom(3, 13));
?>

The above will output two different random numbers in an array:
 Array ( [0] => 5 [1] => 7 )
polmme at hotmail dot com
03-Feb-2005 12:10
Why not just like this....

<?

//author: polmme

$codelenght = 10;
while(
$newcode_length < $codelenght) {
$x=1;
$y=3;
$part = rand($x,$y);
if(
$part==1){$a=48;$b=57;}  // Numbers
if($part==2){$a=65;$b=90;}  // UpperCase
if($part==3){$a=97;$b=122;} // LowerCase
$code_part=chr(rand($a,$b));
$newcode_length = $newcode_length + 1;
$newcode = $newcode.$code_part;
}
echo
$newcode;
?>
webdude at sider dot net
27-Jan-2005 04:32
A very simple random string generator function:

<?
function rand_str($size)
{
  
$feed = "0123456789abcdefghijklmnopqrstuvwxyz";
   for (
$i=0; $i < $size; $i++)
   {
      
$rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
   }
   return
$rand_str;
}

echo
rand_str(10);
?>
relsqui at armory dot com
21-Jan-2005 11:23
Don't forget, it's faster to use bitwise operations when you need a random number that's less than some power of two. For example,

<?php
rand
()&1;
// instead of
rand(0,1);
// for generating 0 or 1,

rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,

rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you're doing there is generating a default random number (so PHP doesn't have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise operation which is faster than even basic math).
Janus - palacecommunity dot com
29-Dec-2004 03:03
Or you could do!:

$rnd = mysql_result(mysql_query("SELECT FLOOR(RAND() * COUNT(*)) FROM `table` (WHERE `condition`)"));

mysql_query("SELECT * FROM `table` (WHERE condition`) LIMIT {$rnd},1");
onno at onnovanbraam dot com
12-Sep-2004 03:58
>>Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.<<

Do realize that you don't HAVE to call srand, but if you don't you get the same results every time... Took me quite a while to get to that conclusion, since I couldn't figure it out:

foreach($Unit AS $index => $value) {
   srand() ;
   $rand_pos_x = rand(0, $EVAC['x_max']) ;
   $rand_pos_y = rand(0, $EVAC['y_max']) ;
}

works, but:

foreach($Unit AS $index => $value) {
   $rand_pos_x = rand(0, $EVAC['x_max']) ;
   $rand_pos_y = rand(0, $EVAC['y_max']) ;
}

doesnt even though they say it should.

I'm using Windows XP Pro (Windows NT EVOLUTION 5.1 build 2600), PHP Version 4.3.3, CGI/FastCGI.
aidan at php dot net
11-Sep-2004 09:45
To easily generate large numbers, or random strings such as passwords, take a look at the below function.

http://aidan.dotgeek.org/lib/?file=function.str_rand.php
a_kunyszSPAM at SUXyahoo dot com
04-Sep-2004 04:44
You won't get true random numbers from a computer but you can get some from a webcam or radioactive material.

http://www.fourmilab.ch/hotbits/ (you can fetch random bits generated from radioactive material from the web here)
http://www.lavarnd.org/ (how to set up a random number generator with a webcam)
jbarbero at u dot washington dot edu
08-Dec-2003 10:14
to jordan at do not spam .com:

The image no-cache function is simpler if you just do:
<?
$junk
= md5(time());
?>

Usage would be: <img src="image.gif?<?=$junk?>">

md5(time()) is more guaranteed to be unique, and it is faster than two md5 calls.
ewspencer at industrex dot com
03-Jun-2003 08:40
Inspired by the many useful tips posted by other users, I wrote a flexible, arbitrary, random character generator, which also produces random color values in decimal or hexadecimal format.

The procedure is encapsulated as a PHP function named randchar().

You're welcome to freely download the randchar() source code at http://www.industrex.com/opensource/randchar.phps
igge at netpond dot com
30-Oct-2002 01:35
About selecting random rows from a MySQL table:

SELECT * FROM tablename ORDER BY RAND() LIMIT 1

works for small tables, but once the tables grow larger than 300,000 records or so this will be very slow because MySQL will have to process ALL the entries from the table, order them randomly and then return the first row of the ordered result, and this sorting takes long time. Instead you can do it like this (atleast if you have an auto_increment PK):

SELECT MIN(id), MAX(id) FROM tablename;

Fetch the result into $a

$id=rand($a[0],$a[1]);

SELECT * FROM tablename WHERE id>='$d' LIMIT 1

<rad2deground>
 Last updated: Fri, 18 Feb 2005
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Fri Feb 18 05:12:01 2005 CET