Hướng dẫn dùng example alphanumeric trong PHP

[PHP 4, PHP 5, PHP 7, PHP 8]

randGénère une valeur aléatoire

Description

rand[]: int

rand[int $min, int $max]: int

Appelée sans les options min et max, rand[] retourne un nombre pseudoaléatoire entre 0 et getrandmax[]. Si vous voulez un nombre aléatoire entre 5 et 15 [inclus], par exemple, utilisez rand [5, 15].

Attention

Cette fonction ne génère pas de valeurs sécurisées d'un point de vue cryptographique, et ne doit pas être utilisée dans un contexte de chiffrement. Si vous avez besoin d'une valeur sécurisée d'un point de vue cryptographique, utilisez plutôt random_int[], random_bytes[], ou openssl_random_pseudo_bytes[].

Note: Sur quelques plates-formes [par exemple, Windows], mt_getrandmax[]est limité à 32767. Si vous désirez une limite supérieure à 32767, en spécifiant min et max, vous serez autorisés à utiliser un intervalle plus grand que mt_getrandmax[], ou bien, utilisez la fonction mt_rand[] à la place.

Note: À partir de php 7.1.0, rand[] utilise le même générateur de nombres aléatoires que mt_rand[]. Pour préserver la compatibilité ascendante, rand[] permet à max d'être plus petit que min par opposition au retour false de mt_rand[]

Liste de paramètres

min

La plus petite valeur à retourner [par défaut, 0]

max

La plus grande valeur à retourner [par défaut, mt_getrandmax[]]

Valeurs de retour

Une valeur pseudoaléatoire, comprise entre min [ou 0] et max [ou mt_getrandmax[], inclusif].

Historique

VersionDescription
7.2.0 rand[] a reçu une correction de bogue pour un bug de polarisation modulo. Cela signifie que les séquences générées dans certain cas spécifiques peuvent différer de php 7.1 sur les machines 64-bit.
7.1.0 rand[] a été fait un alias de mt_rand[].

Exemples

Exemple #1 Exemple avec rand[]

Résultat de l'exemple ci-dessus est similaire à :

Notes

Avertissement

La plage min max doit se situer dans la plage getrandmax[]. i.e. [max - min]

If you don't want the same character to appear beside itself, use this:



For those of you who want both as a function, use this:



string $c is the string of characters to use.
integer $l is how long you want the string to be.
boolean $u is whether or not a character can appear beside itself.

Examples:
rand_chars["ABCEDFG", 10] == GABGFFGCDA
rand_chars["ABCEDFG", 10, TRUE] == CBGFAEDFEC

relsqui at armory dot com

17 years ago

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,



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].

petabyte.se

13 years ago

As an further optimization on janoserki[at]gmail[dot]com previous post i would recommend that you optimize you first part of php/sql code to something like this.


the count[*] is much faster for the database than grabbing the hole dataset from the table.

Alireza Eliaderani

11 years ago

Random integers with normal distribution,
it's not scientifically approved, but worked for me.

Justin Richer

10 years ago

Since many people [myself included] come to this page looking for a way to do a random string, I present a way that uses arrays and shuffle[] instead of rand[]. This also has the effect of not repeating any characters in the value set.

    $arr = str_split['ABCDEFGHIJKLMNOP']; // get all the characters into an array
    shuffle[$arr]; // randomize the array
    $arr = array_slice[$arr, 0, 6]; // get the first six [random] characters out
    $str = implode['', $arr]; // smush them back into a string

jont at live dot co dot uk

15 years ago

isn't this just a simpler way of making a random id for somthing? I mean i know that there is a very slight chance that a duplicate could be made but its a very, very, very small chance, nearly impossible.

$rand = mt_rand[0, 32];
$code = md5[$rand . time[]];
echo "$code";

and if you don't want it the md5 can be removed, I've just added it as a prefer it there :]

Jon

janoserki [at] gmail [dot] com

13 years ago

Easy way for mysql: random row
the original form is: "... order by rand[]"
but this is not the best way, because it's very slow by a big database [it can take more minutes to complete the request!]
My suggestion:

matheus at matheusloureiro dot com

9 years ago

If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function:

abdufarag at yahoo dot com

1 year ago

I have made this example to generate random number with specific length [10].

razvan_bc at yahoo dot com

3 years ago

well ,

this is my vision about "custom random string" :

Wirek

7 years ago

I agree with Sebmil [//php.net/manual/en/function.array-rand.php#105265] that "array_rand[]" produces weird and very uneven random distribution [as of my local PHP 5.3.8 and my public host's PHP 5.2.17].
Unfortunately, I haven't got any access either to a server with the latest PHP version. My info is for those of you who like to check things for themselves and who don't believe all of the official statements in the docs.
I've made a simple adjustment of his test code like this:


And it appears to me that simple "$idx=rand[0, count[$test]-1];" is much better than "$idx=array_rand[$test, 1];".
And what's more the simpler and a bit slower [0 ms up to total 712.357 ms at 5 mln cycles] "rand[]" is better than "mt_rand[]" in simple everyday use cases because it is more evenly distributed [difference least vs. most often numbers: ca. 0.20-1.28 % for "rand[]" vs. ca. 1.43-1.68 % for "mt_rand[]"].
Try it for yourself... although it depends on your software and hardware configuration, range of numbers to choose from [due to random patterns], number of cycles in the loop, and temporary [public] server load as well.

Hayley Watson

9 years ago

The Windows rand[] function is quite a lot worse than merely having a low maximum value. It's an ordinary Linear Congruential Generator, which means you only need three consecutive values to be able to predict its entire future output.

Given the numbers 13050,  4267,  25352, construct the equations
4267 = [13050a+c] % 32768
25352 = [4267a+c] % 32768

Solving for a and c gives

a = 20077
c = 12345

Which means the next number that should be spat out is [25352×20077+12345] % 32768 = 19105 -- which indeed it is.

It's not the small rand_max that breaks the algorithm, it's a weakness in the  LCG algorithm itself. It's designed for when you only want a few kinda-random numbers occasionally, not if you want to generate any random-looking data.

Hugo Scott hrmscott at hotmail dot com

13 years ago

Here's a simple function to generate a random date between a start date and an end date.

It is inclusive of BOTH dates - so using dates 2009-04-01 and 2009-04-03 would generate a random date that could be 2009-04-01, 2009-04-02 or 2009-04-03.

It won't work if the end date is prior to the start date and if you use a non-existant date [eg 2009-02-30] it defaults to 1970-01-01

the longer version:


and the one-line version for compactness freaks:


it is called like this

Hope this is of some use to someone

opbarnes

13 years ago

Generate a random 5 character alpha string:

bozo_z_clown at yahoo dot com

15 years ago

Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server.  Either call srand[] yourself with a more frequently changing seed or use mt_rand[] which doesn't appear to suffer from the problem.

pasafama at gmail dot com

5 years ago

From PHP 7.1 rand[] is documented as an alias of mt_rand[].

Actually, if they are called with two arguments where the second is smaller than the first, their output differs.

For example

var_dump[rand[2,1], mt_rand[2,1]];

may return

Warning: mt_rand[]: max[1] is smaller than min[2]
int[2]
bool[false]

where rand[] will return a random value between $max and $min

Anonymous

14 years ago

quick way to generate randomish numbers and simple strings.
no messing around with functions, so you can just pop the line into the middle of your existing code.

not the most perfect for sure, but ok for plenty of situations...



hope someone finds it useful for somthing.

regards,
deeeeeen alxndr0u

John Galt

12 years ago

Another way to create an array of random numbers where there are no identical numbers.

[$n = number of random numbers to return in the array
$min = minimum number
$max = maximum number]

thibault dot debatty at gmail dot com

10 years ago

In Suhosin version 0.9.26 [released 2008.08.22] and above:
- rand[] and srand[] are transparently modified to use the Mersenne Twister algorithm with separate state
- rand[] and mt_rand[] have better internal seeding
- srand[] and mt_srand[] are ignored [can be configured]

davidsteinsland [at] gmail [dot] com

14 years ago

emad_ramahi at hotmail dot com:
I've actually noticed that with a large dataset [100k rows], the query dramatically slows down the server and performance is way too bad.

The way I see it, you have to workable solutions:

Using PHP:

Zak

10 years ago

I couldn't find a suitable random alpha-numeric generator function so I rolled my own. It gives a random number in base 36 [0-9, a-z] to a given length.



hopefully helps someone

mparsa1372 at gmail dot com

1 year ago

Change Background Color With Rand[] And Style :

matthias dot isler at gmail dot com

10 years ago

I had to create a function that generates a random binominal distributed integer. Take a look at the following Wiki article:

//en.wikipedia.org/wiki/Binomial_distribution

Here is my solution:

Anonymous

12 years ago

Generate a random 5 character A-Z0-9  string



# php -r 'for [$i=0; $i

I expected to get pixel noise, but instead one can see plain diagonal lines.

admin at djs-music dot com

13 years ago

A nice function to generate a random string, using any character:



Simply use:
generateRandStr[10];

Sample output: $%29zon[4f

simon at labs dot coop

8 years ago

Something we discovered in Sydney running BBS Systems before the net advent was here, if we didn't seed of another BBS we would going in circles in our System Physicality Abstraction Layers.. The important thing is to seed from a remote system and easy way at the Centroidal Plexus of the web [Chronolabs Cooperative] we offer a seed feed and the following code will randomise you out of the number cycle:

See in PHP both the letters and numbers are seedable as letters are treated as numbers as well. You can always use individual tokens by extracting the Element with DOM.. But below is equally effective!

szeryf.wordpress.com

11 years ago

Much easier way to generate random string of numbers and letters:



This generates strings of about 11 characters. Experiment with the range for rand[] if you want shorter or longer.

Greg R.

13 years ago

I thought this function [random color] might be of use to someone [to create and return a random hex for HTML colors]:

liveonaware [at] gmail [dot] com

12 years ago

smaaps at kaldamar dot de

17 years ago

Lately I needed some random numbers with a gaussian [normal] distribution, not evenly distributed as the numbers generated by rand[]. After googling a while, I found out that there is no perfect algrorithm that creates such numbers out of evenly distruted random numbers but a few methods that have similar effect. The following function implements all three algorithms I found- The the last two methods create numbers where you can find a lower and upper boundary and the first one will create a number from time to time [such as one in every 10000] that may be very far from the average value. Have fun testing and using it.

Anonymous

1 year ago

Note that the algorithm change in version 7.1.0 broke the repeatability of a random sequence initialized with a given value. For example if you have a program like:



It will will no longer produce the same results after version 7.1.0. This can be very important for some kinds of simulations. Hopefully you were using mt_rand[] or something better all along, otherwise you will have some digging to do if you want your program to be able to repeat simulations from the pre-7.1.0 days... You will need to look in the PHP source archives to discover the algorithm they used to use and replicate it in your program.

Chủ Đề