Randomise elements in PHP array with shuffle is quite easy. I have to spend at least an hour to optimise this task until I found shuffle function what already done this task :).
The function reference you can check more detail here: http://php.net/manual/en/function.shuffle.php
Here is an example for how to randomise elements in PHP array with shuffle
Let ‘s run this code
1 2 3 4 5 | <?php $natural_born_killers = array("lions", "tigers", "bears", "kittens"); shuffle($natural_born_killers); var_dump($natural_born_killers); ?> |
Run in many times and try to see the result array, it will show you different result every time you run it.
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:
1 2 3 4 | <?php $natural_born_killers = array("lions", "tigers", "bears", "kittens"); var_dump(array_rand($natural_born_killers, 2)); ?> |