void shuffle ( array input)
mixed array_rand ( array input [, int num_req])
Very often you will find yourself not wanting to read from your array in a strictly ordered fashion, and in this situation you need to make use of either shuffle() or array_rand().
Shuffle() takes the entire array and randomises the position of the elements in there. In earlier versions of PHP the shuffle() algorithm was not very good, leading the "randomisation" to be quite weak, however that problem is now fixed.
Take a look at this example:
<?php $natural_born_killers = array("lions", "tigers", "bears", "kittens"); shuffle($natural_born_killers); var_dump($natural_born_killers); ?>
One major drawback to using shuffle() is that it mangles your array keys. This is unavoidable sadly, and you need to live with it when you use shuffle(). Note that shuffle uses its parameter by reference - it returns true, but shuffles up the parameter you pass to it.
If you want to pick out just one random value from an array, you can use array_rand() - it takes an array to read from, then returns one random key from inside there. The advantage to array_rand() is that it leaves the original array intact - you can use the random key returned to grab the related value from the array, but other than that the original array is left untouched.
Array_rand() has an optional second parameter that allows you to specify the number of elements you would like returned. These are each chosen randomly from the array, and are not necessarily returned in any particular order.
Before I show you an example, you need to be aware of the following attributes of array_rand():
It returns the keys in your array. If these aren't specified, the default integer indexes are used. To get the value out of the array, just look up the value at the key.
If you ask for one random element, or do not specify parameter two, you will get a standard variable back.
If you ask for more than one random element, you will receive an array of variables back.
If you ask for more random elements than there are in the array you will get an error
Array_rand() will not return duplicate elements if you request more than one random element
If you want to read most or all of the elements from your array in a random order, use a mass-randomiser like shuffle() - it is faster.
With that in mind, here's an example of array_rand() in action:
<?php $natural_born_killers = array("lions", "tigers", "bears", "kittens"); var_dump(array_rand($natural_born_killers, 2)); ?>
Next chapter: Creating an array of numbers >>
Previous chapter: Grabbing keys and values
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.