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:
<?php array_rand(array_flip($array), $n); ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
array_rand — Prend une ou plusieurs clés, au hasard dans un tableau
$array
, int $num
= 1): int|string|arraySélectionne une ou plusieurs valeurs au hasard dans un tableau et retourne la ou les clés de ces valeurs.
Cette fonction ne génère pas de valeurs cryptographiquement sûres, et ne doit pas être utilisée à des fins cryptographiques, ou à des fins qui exigent que les valeurs renvoyées soient indéchiffrables.
Si de l'aléatoire cryptographiquement sûre est requis, le Random\Randomizer peut être utilisé avec le moteur Random\Engine\Secure. Pour des cas d'usage simple, les fonctions random_int() et random_bytes() fournissent une API pratique et sûre qui est qui est soutenu par le CSPRNG du système d'exploitation.
array
Le tableau d'entrée.
num
Spécifie le nombre d'entrées que vous voulez récupérer.
Lorsque vous ne récupérez qu'une seule entrée, la fonction
array_rand() retourne la clé d'une entrée choisie
aléatoirement. Sinon, un tableau de clés d'entrées aléatoires sera
retourné. Cela vous permet de faire une sélection au hasard de clés,
ou bien de valeurs. Si plusieurs clés sont retournées, alors elles le
seront dans l'ordre qu'elles étaient dans le tableau d'origine
Le fait de tenter de récupérer plus d'éléments
qu'il n'y en a dans le tableau fera qu'une erreur de niveau
E_WARNING
sera émise, et NULL sera retourné.
Version | Description |
---|---|
7.1.0 | L'algorithme interne de génération aléatoire a été modifié pour utiliser le générateur aleatoire de nombre » Mersenne Twister au lieu de la fonction aléatoire libc |
Exemple #1 Exemple avec array_rand()
<?php
$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";
?>
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:
<?php array_rand(array_flip($array), $n); ?>
It doesn't explicitly say it in the documentation, but PHP won't pick the same key twice in one call.
<?php
/**
* 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)]);
}
<?php
// 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 ) ) ) ) );