Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random value out of an array?

Tags:

arrays

php

random

People also ask

Can you use math random on array?

random() Let's write a function to return a random element from an array. We can use Math. random() to generate a number between 0–1 (inclusive of 0, but not 1) randomly.

How do you randomize an array?

Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...


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.


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)];

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;
}

$value = $array[array_rand($array)];

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)];

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)