Articles

The month of PHP functions : random PHP

  • Ecrit par Damien Seguy
  • jeudi 12 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


Most of the time, software are made to sort things out, and give data consistency. Data are analysed, validated and undergo all kind of business rules. When they are not good enough, they may be processed to be corrected.

Then why are there some many functions to introduce ranfom values in a piece of software? They are here to solve a fair number of business problems. Randomness is usually called upon when humans can't find anymore solution : pieces are taken in random order and when it is not satisfactory, then, blame is on randomness. In PHP, there are two kind of random functions : the producers, and the mixers.

Producers are random number generators. This mean functions such as the popular rand(), which returns a random value between 0 and RAND_MAX. RAND_MAX is a PHP constant, which defines the largest random integer possible. You may use this constant to bring back random numbers between 0 and 1. When RAND_MAX does not exists, rely upon getmaxrand().

And if you want your integer in a specific range, you may just specify the limits as arguments.

<?php
 
 
echo <a href="http://www.php.net/rand">rand()</a>; 
echo <a href="http://www.php.net/rand">rand()</a> / <a href="http://www.php.net/getmaxrand">getmaxrand()</a>; // between 0 and 1
echo rand(4,5); // either 4, or 5
 
 
srand(1);
echo <a href="http://www.php.net/rand">rand()</a>; // a number
srand(1);
echo <a href="http://www.php.net/rand">rand()</a>; // same number
 
 
?>

Calling srand() isn't necessary, as PHP will call it for you by default. Seeding the random number generator is a way to reproducing random sequences. This is useful to feed a test programm with random values, and replay the actual sequence later. When testing software which need to be predictives, it is useful to send random values.

The rand() functions family may be replaced by the same functions, with the mt_prefix. According to the documentation, mt_rand() uses a light library, which is less predictive than the one for rand(). Practically speaking, it is difficult to make a difference between the two functions, expect may be on some specifi palt-form. All in all, don't over optimize your application with this prefix.

The random number generator is not fit for array manipulations. Obviously, one may use random numbers as index in an array, and reach random values, but it is all so easier to let array_rand() do the job

When used with one argument, array_rand() will return a index, chosen among the one available.  When used with 2 arguments, array_rand() returns an array of index, with as many elements as requested.

<?php
 
 
$t = array('a' => 2, 'b' => 3, 'c' => 4);
print array_rand($t)."\n";
print_r(array_rand($t,2));
 
 
?>

This script might display :

b
Array
(
    [0] => a
    [1] => b
)

array_rand() returns a list of keys, which is good when you're using an associative array. This way, you get the key and the value easily. If you're interested only by the values, this is an extra step. The easiest is to use array_flip() to flip the array : the only condition for this trick is to make sure the values are unique, otherwise, it will unbalance probabilities.

<?php
 
 
$t = range('a','g');
print_r(array_rand(array_flip($t),2)); // returns directly letters
 
 
 
 
 
 
$t = array('a','a','a','a','b','c','d');
print_r(array_rand(array_flip($t),2)); // will never get a double 'a' array
 
 
?>

Last, there are the shuffling functions : they work on the spot, and apply a random order to the variable. This exists for arrays and for strings.

<?php
$t = range('a','f');
shuffle($t);
 
 
print_r($t);
 
 
sort($t);
$c = join('', $t);
print str_shuffle($c);
 
 
?>

This script will display something like :
Array
(
    [0] => e
    [1] => b
    [2] => f
    [3] => c
    [4] => a
    [5] => d
)
dfaebc

This system is fit for  draws, where everyone has to get a ranking, such as the initial racing order. This way, there won't be any double, unless you want them. On the other hand, this will be less suited for generating passwords, as the non-double policy will weaken the password.

To be noted
  • Some functions were introduced in PHP 5, or even PHP 5.2.
  • shuffle(), just like sort(), work on the spot, and it doesn't return anything.
  • One generate random numbers, and less often strings. You have then to rely on a transformation function to turn your numbers into strings, such as ord().

< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter