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 — Liefert einen oder mehrere zufällige Schlüssel eines Arrays
Wählt einen oder mehrere Einträge aus einem Array aus und gibt den Schlüssel des zufälligen Eintrags bzw. die Schlüssel der zufälligen Einträge zurück. Es wird ein Pseudozufallszahlengenerator verwendet der nicht für kryptographische Zwecke geeignet ist.
array
Das Eingabe-Array.
num
Gibt an, wie viele Einträge ausgewählt werden sollen.
Wenn nur ein Eintrag ausgewählt wird, liefert
array_rand() den Schlüssel eines zufälligen
Eintrages. Andernfalls wird ein Array mit den Schlüsseln der
zufälligen Einträge zurückgegeben. Dies hat den Zweck, dass
zufällige Schlüssel und auch Werte aus dem Array ausgewählt
werden können. Der Versuch mehr Elemente auszuwählen als im Array vorhanden sind,
ergibt einen Fehler der Stufe E_WARNING
und NULL wird zurückgegeben.
Version | Beschreibung |
---|---|
7.1.0 | Zur Erzeugung der Zufallszahlen kommt intern nun der » Mersenne-Primzahlen-Zufallsgenerator statt der vorherigen libc-rand-Funktion zum Einsatz. |
Beispiel #1 array_rand()-Beispiel
<?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
// 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 ) ) ) ) );
<?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)]);
}