156

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?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Elitmiar
  • 35,072
  • 73
  • 180
  • 229

21 Answers21

278

You can also do just:

$k = array_rand($array);
$v = $array[$k];

This is the way to do it when you have an associative array.

reko_t
  • 55,302
  • 10
  • 87
  • 77
  • 11
    according to this [comment](http://www.php.net/manual/en/function.array-rand.php#105265) `array_rand` is not as random as it should be – Timo Huovinen Jun 14 '14 at 09:23
  • 1
    Or you can require [this package](https://github.com/freekmurze/array-functions) and use `array_rand_value` – murze May 20 '15 at 20:25
  • 15
    Since PHP 7.1, [`array_rand()`](http://php.net/manual/en/function.array-rand.php) uses the Mersenne Twister generator: [rand() aliased to mt_rand() and srand() aliased to mt_srand()](http://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.rand-srand-aliases). In practice it should now be good enough. – Gras Double Jun 29 '17 at 11:17
39

PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php

$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
NDM
  • 6,731
  • 3
  • 39
  • 52
27
$value = $array[array_rand($array)];
KAS
  • 790
  • 7
  • 12
24

You can use mt_rand()

$random = $ran[mt_rand(0, count($ran) - 1)];

This comes in handy as a function as well if you need the value

function random_value($array, $default=null)
{
    $k = mt_rand(0, count($array) - 1);
    return isset($array[$k])? $array[$k]: $default;
}
Timo Huovinen
  • 53,325
  • 33
  • 152
  • 143
Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
  • 4
    Should be mt_rand(0, 3) as there are only 4 items. More correctly though: $array[mt_rand(0, count($array)] – reko_t Oct 29 '09 at 12:43
  • 2
    Err, I think you meant mt_rand(0, count($ran) - 1) – Josh Davis Oct 29 '09 at 12:50
  • according to php comments `array_rand` is not as random as it should be, so `mt_rand` is preferred – Timo Huovinen Oct 23 '14 at 09:00
  • 1
    What's the point in the whole `isset` part? This would fail for associative arrays anyway. – Luke Cousins Jan 18 '15 at 12:32
  • i don't know why, but when using `mt_rand` instead of `rand` in this case seems to prefer some items more than the others – user151496 Jun 09 '16 at 14:02
  • since PHP 7.1 array_rand uses Mersenne Twister algorithm http://php.net/manual/en/function.array-rand.php – Jan Richter May 02 '18 at 02:50
  • Despite this answer being 10 years old, one could obtain the array keys and *then* get a random key from that array. If you do `$keys = array_keys($array);` and then `$key = mt_rand(0, count($keys) - 1);`, the variable `$key` will have a random index from the array `$keys`, which returns a key to be used for the `$array`. Something like `return $array[$keys[$key]];`. This will work for associative, numeric and mixed arrays. Try it on http://sandbox.onlinephpfunctions.com/code/455d7a75d1b0951e29adf9a319e7da3678468ca2 (remove the type hinting for compatibility with PHP 5.0 and older) – Ismael Miguel Aug 01 '19 at 08:24
19

You could use the array_rand function to select a random key from your array like below.

$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];

or you could use the rand and count functions to select a random index.

$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];
TURTLE
  • 3,728
  • 4
  • 49
  • 50
13

Derived from Laravel Collection::random():

function array_random($array, $amount = 1)
{
    $keys = array_rand($array, $amount);

    if ($amount == 1) {
        return $array[$keys];
    }

    $results = [];
    foreach ($keys as $key) {
        $results[] = $array[$key];
    }

    return $results;
}

Usage:

$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];

array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']

A few notes:

  • $amount has to be less than or equal to count($array).
  • array_rand() doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Use shuffle() 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:

function array_random($array, $number = null)
{
    $requested = ($number === null) ? 1 : $number;
    $count = count($array);

    if ($requested > $count) {
        throw new \RangeException(
            "You requested {$requested} items, but there are only {$count} items available."
        );
    }

    if ($number === null) {
        return $array[array_rand($array)];
    }

    if ((int) $number === 0) {
        return [];
    }

    $keys = (array) array_rand($array, $number);

    $results = [];
    foreach ($keys as $key) {
        $results[] = $array[$key];
    }

    return $results;
}

A few highlights:

  • Throw exception if there are not enough items available
  • array_random($array, 1) returns an array of one item (#19826)
  • Support value "0" for the number of items (#20439)
Gras Double
  • 15,901
  • 8
  • 56
  • 54
11

Another approach through flipping array to get direct value.

Snippet

$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));

array_rand return key not value. So, we're flipping value as key.

Note: PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.

Shahnawaz Kadari
  • 1,423
  • 1
  • 12
  • 20
  • Why not just do `$array[array_rand($array)];`? – rinogo Mar 12 '19 at 19:20
  • @rinogo It's works too, This already answered above. This is little bit different from your answer, `array_flip` remove duplicate as key then give result... Mean no duplicate! – Shahnawaz Kadari Mar 13 '19 at 03:48
  • To escape duplicate keys you can use this syntax (In the second row): `$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jane' ]; $val = array_rand(array_flip(array_unique($array)));` – איש נחמד Sep 19 '21 at 07:45
10

The array_rand function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:

$myArray = array(1, 2, 3, 4, 5);

// Random shuffle
shuffle($myArray);

// First element is random now
$randomValue = $myArray[0];
Asciiom
  • 9,867
  • 7
  • 38
  • 57
  • That's a lot of extra computational "work" just to get a single random element, though. The other answers that use `mt_rand()` are probably better suited to the task. – rinogo May 02 '19 at 20:45
  • Depends on what your needs are, I suppose. In my case, distribution was very important and the computational overhead was not. – Asciiom May 03 '19 at 08:03
6
$rand = rand(1,4);

or, for arrays specifically:

$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
Duroth
  • 6,315
  • 2
  • 19
  • 23
6

On-liner:

echo $array[array_rand($array,1)]
Sid
  • 4,302
  • 3
  • 26
  • 27
4

In my case, I have to get 2 values what are objects. I share this simple solution.

$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));
CN Lee
  • 124
  • 3
3

One line: $ran[rand(0, count($ran) - 1)]

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
Abdelilah
  • 37
  • 3
3

This will work nicely with in-line arrays. Plus, I think things are tidier and more reusable when wrapped up in a function.

function array_rand_value($a) {
    return $a[array_rand($a)];
}

Usage:

array_rand_value(array("a", "b", "c", "d"));

On PHP < 7.1.0, array_rand() uses rand(), so you wouldn't want to this function for anything related to security or cryptography. On PHP 7.1.0+, use this function without concern since rand() has been aliased to mt_rand().

rinogo
  • 8,491
  • 12
  • 61
  • 102
3

I needed one line version for short array:

($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]

or if array is fixed:

[1, 2, 3, 4][mt_rand(0, 3]
Rafael
  • 326
  • 2
  • 6
2

Does your selection have any security implications? If so, use random_int() and array_keys(). (random_bytes() is PHP 7 only, but there is a polyfill for PHP 5).

function random_index(array $source)
{
    $max = count($source) - 1;
    $r = random_int(0, $max);
    $k = array_keys($source);
    return $k[$r];
}

Usage:

$array = [
    'apple' =>   1234,
    'boy'   =>   2345,
    'cat'   =>   3456,
    'dog'   =>   4567,
    'echo'  =>   5678,
    'fortune' => 6789
];
$i = random_index($array);
var_dump([$i, $array[$i]]);

Demo: https://3v4l.org/1joB1

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
2

Use rand() to get random number to echo random key. In ex: 0 - 3

$ran = array(1,2,3,4);
echo $ran[rand(0,3)];
Muhammad Ibnuh
  • 360
  • 5
  • 14
0

I'm basing my answer off of @ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:

function &random_value(&$array, $default=null)
{
    $k = mt_rand(0, count($array) - 1);
    if (isset($array[$k])) {
        return $array[$k];
    } else {
        return $default;
    }
}

For more context, see my question over at Passing/Returning references to object + changing object is not working

Community
  • 1
  • 1
Jeff
  • 13,943
  • 11
  • 55
  • 103
0

Get random values from an array.

function random($array)
{
    /// Determine array is associative or not
    $keys = array_keys($array);
    $givenArrIsAssoc = array_keys($keys) !== $keys;

    /// if array is not associative then return random element
    if(!$givenArrIsAssoc){
        return $array[array_rand($array)];
    }

    /// If array is associative then 
    $keys = array_rand($array, $number);
    $results = [];
    foreach ((array) $keys as $key) {
        $results[] = $array[$key];
    }
    return $results;
}
dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
0

mt_srand usage example

if one needs to pick a random row from a text but same all the time based on something

$rows = array_map('trim', explode("\n", $text));
mt_srand($item_id);
$row = $rows[rand(0, count($rows ) - 1)];
Hebe
  • 661
  • 1
  • 7
  • 13
-1

A simple way to getting Randdom value form Array.

$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)

now every time you will get different colors from Array.

pankaj
  • 1
  • 17
  • 36
-5

You get a random number out of an array as follows:

$randomValue = $rand[array_rand($rand,1)];
Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39