Php array random key

Get random elements from an array in PHP

This post will discuss how to generate random entries from an array in PHP.

1. Using array_rand() function

A simple and efficient solution is to use the array_rand() function to pick one or more random entries out of an array. Here’s a PHP program to pick a random key from an array $arr :

The array_rand() function returns the key of the random entry. To select a random value (not a key) of the random entry, use the snippet below:

Here’s an example using a closure.

The second argument of the array_rand() function specifies how many random entries should be picked. Here’s a PHP program to pick $n random values from an array $arr :

2. Using mt_rand() function

Before PHP 7.1.0, the internal randomization algorithm for array_rand() uses the libc rand function, which is slower and less-random than Mersenne Twister Number Generator. If your array keys are numeric, here’s a better alternative to pick a random value from an array $arr :

The mt_rand() function is a better alternative for the older rand() . However, both array_rand() and mt_rand() does not generate cryptographically secure values. For cryptographic purposes, consider using random_int() , random_bytes() , or openssl_random_pseudo_bytes() instead.

Читайте также:  How to set image in html as background

Refer to PHP Manual for more details.

That’s all about generating random entries from an array in PHP.

Average rating 4.92 /5. Vote count: 12

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Источник

array_rand

Выбирает одно или несколько случайных значений из массива. Возвращает ключ (или ключи) данных случайных элементов.

Функция не создаёт криптографически защищённые значения и не должна использоваться для криптографических целей или целей, требующих, чтобы возвращаемые значения были недоступны для разгадывания.

Если требуется криптографически безопасная случайная последовательность, Random\Randomizer может использоваться с движком Random\Engine\Secure . Для простых случаев использования функции random_int() и random_bytes() предоставляют удобный и безопасный API, поддерживаемый CSPRNG операционной системы.

Список параметров

Определяет количество выбираемых элементов.

Возвращаемые значения

Если вы выбираете только одно значение, функция array_rand() возвращает ключ, соответствующий этому значению. В обратном случае, она возвращает массив ключей, соответствующих случайным значениям. Это сделано для того, чтобы дать возможность выбрать из массива как случайные значения, так и случайные ключи. Если возвращается несколько ключей, они будут возвращены в том порядке, в котором они присутствовали в исходном массиве. Попытка выбрать больше элементов, чем есть в массиве, сгенерирует ошибку уровня E_WARNING и вернёт NULL.

Список изменений

Версия Описание
7.1.0 Внутренний алгоритм получения случайных чисел изменён с функции rand библиотеки libc на генератор на базе » Вихря Мерсенна.

Примеры

Пример #1 Пример использования array_rand()

$input = array( «Neo» , «Morpheus» , «Trinity» , «Cypher» , «Tank» );
$rand_keys = array_rand ( $input , 2 );
echo $input [ $rand_keys [ 0 ]] . «\n» ;
echo $input [ $rand_keys [ 1 ]] . «\n» ;
?>

Смотрите также

User Contributed Notes 7 notes

If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

It doesn’t explicitly say it in the documentation, but PHP won’t pick the same key twice in one call.

array_rand () takes a random value without ever being able to go back in its choice of random value.
A simple example:
I decide to mix an array of 10 entries to retrieve 3 values. This choice will give increasing and random values.

$pm = array_rand($myarray,3);
// $pm return array(0->0,1->6,2->8)

But if I decide to shuffle an array of 10 entries to get 10 entries, array_rand () will choose to assign a value to each return value and therefore the return array will not be random.

$gm = array_rand($myarray,count($myarray));
// $gm not random array(0->0,1->1,2->2,3->3,4->4,5->5,6->6,7->7,8->8,9->9)

The easiest way to have a truly random value:
either use array_rand () in a loop of 1 value at a time

——————
or simply use shuffle () to shuffle the array really randomly.

/**
* Wraps array_rand call with additional checks
*
* TLDR; not so radom as you’d wish.
*
* NOTICE: the closer you get to the input arrays length, for the n parameter, the output gets less random.
* e.g.: array_random($a, count($a)) == $a will yield true
* This, most certainly, has to do with the method used for making the array random (see other comments).
*
* @throws OutOfBoundsException – if n less than one or exceeds size of input array
*
* @param array $array – array to randomize
* @param int $n – how many elements to return
* @return array
*/
function array_random (array $array , int $n = 1 ): array
if ( $n < 1 || $n >count ( $array )) throw new OutOfBoundsException ();
>

return ( $n !== 1 )
? array_values ( array_intersect_key ( $array , array_flip ( array_rand ( $array , $n ))))
: array( $array [ array_rand ( $array )]);
>

// An example how to fetch multiple values from array_rand
$a = [ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’ , ‘g’ ];
$n = 3 ;

// If you want to fetch multiple values you can try this:
print_r ( array_intersect_key ( $a , array_flip ( array_rand ( $a , $n ) ) ) );

// If you want to re-index keys wrap the call in ‘array_values’:
print_r ( array_values ( array_intersect_key ( $a , array_flip ( array_rand ( $a , $n ) ) ) ) );

for a cryptographically secure version, try

/**
* fetch a random key from array, using a cryptograpically secure rng
* discussed+reviewed at https://codereview.stackexchange.com/questions/275832/cryptographically-secure-version-of-the-core-array-rand-function/
*
* @param array $array
* @throws ValueError if array is empty
* @return int|string key
*/
function array_rand_cryptographically_secure (array $array ) /*: int|string*/ $max = count ( $array ) — 1 ;
if ( $max < 0 ) throw new ValueError ( 'Argument #1 ($array) cannot be empty' );
>
return key ( array_slice ( $array , random_int ( 0 , $max ), 1 , true ) );
>

$tests = [
[ 5 , 6 , 7 ],
[ ‘a’ => 1 , ‘b’ => 2 , ‘c’ => 3 ],
[ ‘zero’ , 4 => ‘four’ , 9 => ‘nine’ ],
[ «PEAN» => 0 ],
[]];
foreach ( $tests as $test ) echo array_rand_cryptographically_secure ( $test ) . «\n» ;
>

?>
(this is an improved version, which unlike the first version, avoids copying *all* the keys)

Generate random index in weights array.
Implementation of Vose’s Alias Method.

class AliasMethod
protected $count ;
protected $prob ;
protected $alias ;

public function __construct ( $weight )
$count = count ( $weight );
$sum = array_sum ( $weight );
$d = $count / $sum ;
$small = [];
$large = [];

while (!empty( $small ) AND !empty( $large )) $l = array_pop ( $small );
$g = array_pop ( $large );
$prob [ $l ] = $weight [ $l ];
$alias [ $l ] = $g ;

if ( ( $weight [ $g ] += $weight [ $l ] — 1 ) < 1 )
$small [] = $g ;
else
$large [] = $g ;
>

foreach ( $large as $i )
$prob [ $i ] = 1 ;

foreach ( $small as $i )
$prob [ $i ] = 1 ;

$this -> prob = $prob ;
$this -> alias = $alias ;
$this -> count = $count ;

public function next (): int
$i = mt_rand ( 0 , $this -> count — 1 );
if ( mt_rand () / mt_getrandmax () prob [ $i ])
return $i ;
else
return $this -> alias [ $i ];
>
>

$weight = [ 1 , 2 , 1 , 1 , 100 , 1 , 1 , 5 , 1 , 1 ];
$rnd = new AliasMethod ( $weight );

$results = array_fill ( 0 , count ( $weight ), 0 );

for( $i = 0 ; $i < 100000 ; ++ $i ) $results [ $rnd -> next ()]++;
>
print_r ( $results );

  • Функции для работы с массивами
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    PHP array_rand() Function

    The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.

    Syntax

    Parameter Values

    Parameter Description
    array Required. Specifies an array
    number Optional. Specifies how many random keys to return

    Technical Details

    Return Value: Returns a random key from an array, or an array of random keys if you specify that the function should return more than one key
    PHP Version: 4+
    PHP Changelog: PHP 7.1: rand() uses the Mersenne Twister random number generator
    PHP 5.2.1: The resulting array of keys is no longer shuffled
    PHP 4.2: The random number generator is seeded automatically

    More Examples

    Example

    Return a random key from an array:

    Example

    Return an array of random string keys:

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    Report Error

    If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

    Thank You For Helping Us!

    Your message has been sent to W3Schools.

    Top Tutorials
    Top References
    Top Examples
    Get Certified

    W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

    Источник

    PHP array_rand() – Get Key(s) Randomly Out of Array

    In this tutorial, you shall learn about PHP array_rand() function which can get us a random key from an array, with syntax and examples.

    PHP array_rand() Function

    The PHP array_rand() function returns a random key from an array. Or you can tell array_rand() to return a specific number of keys taken from an array randomly. In case array_rand() returns multiple keys, it returns them as array.

    Syntax of array_rand()

    The syntax of array_rand() function is

    PHP array_rand() - Get Random Key from Array

    2. Get array of random keys from Array

    In this example, we will take an associative array with key-value pairs. We will call array_rand() function to return 3 keys picked randomly from the array.

    PHP Program

    21, "b"=>54, "m"=>35, "k"=>66); $number = 3; $keys = array_rand($array1, $number); print_r($keys); ?>

    array_rand() returns keys of the original array as values in indexed array.

    PHP array_rand() - Get Array of Random Keys from Array

    You can access the individual keys using index.

    Conclusion

    In this PHP Tutorial, we learned how to , using PHP Array array_rand() function.

    Источник

Оцените статью