I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php
You get a random number out of an array as follows:
Does your selection have any security implications? If so, use
random_int()
andarray_keys()
. (random_bytes()
is PHP 7 only, but there is a polyfill for PHP 5).Usage:
Demo: https://3v4l.org/1joB1
Derived from Laravel
Collection::random()
:Usage:
A few notes:
$amount
has to be less than or equal tocount($array)
.array_rand()
doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Useshuffle()
afterwards if needed.Documentation:
array_rand()
,shuffle()
edit: The Laravel function has noticeably grown since then, see Laravel 5.4's
Arr::random()
. Here is something more elaborate, derived from the grown-up Laravel function:A few highlights:
array_random($array, 1)
returns an array of one item (#19826)You can use mt_rand()
This comes in handy as a function as well if you need the value
You can also do just:
This is the way to do it when you have an associative array.