If you don't want to shuffle()
the entire array (perhaps because your array is relatively large), you can call array_rand()
to populate an array of keys then filter the input array using that array of keys.
Code: (Demo)
$input = [
['filename' => 'a.php', 'description' => 'foo'],
['filename' => 'b.php', 'description' => 'fooey'],
['filename' => 'c.php', 'description' => 'bar'],
['filename' => 'd.php', 'description' => 'berry'],
['filename' => 'e.php', 'description' => 'buoy'],
['filename' => 'f.php', 'description' => 'barf'],
['filename' => 'g.php', 'description' => 'food'],
['filename' => 'h.php', 'description' => 'foodie'],
['filename' => 'i.php', 'description' => 'boof'],
['filename' => 'j.php', 'description' => 'boogey'],
['filename' => 'k.php', 'description' => 'fudge'],
['filename' => 'l.php', 'description' => 'fudgey'],
['filename' => 'm.php', 'description' => 'barge'],
['filename' => 'n.php', 'description' => 'buggy'],
['filename' => 'o.php', 'description' => 'booger'],
['filename' => 'p.php', 'description' => 'foobar'],
['filename' => 'q.php', 'description' => 'fubar'],
['filename' => 'r.php', 'description' => 'goof'],
['filename' => 's.php', 'description' => 'goofey'],
['filename' => 't.php', 'description' => 'boofey'],
];
var_export(
array_intersect_key(
$input,
array_flip(
array_rand($input, 10)
)
)
);
The output, you will notice, has only 10 rows of randomly selected data in it.
Different from shuffle()
, because $input
is nominated first in array_intersect_key()
, the "random" items are actually in their original order.
Even if you iterate array_rand()
's returned array with a classic loop, the results will still be ordered by their position in the original array.
Code: (Demo)
$randoms = [];
foreach (array_rand($input, 10) as $key) {
$randoms[] = $input[$key];
}
var_export($randoms);
If the position of the random elements is important, you should call shuffle()
on the randomly selected results.
Note that the PHP manual says the following for array_rand()
:
[array_rand()] uses a pseudo random number generator that is not suitable for cryptographic purposes.
When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values.
If multiple keys are returned, they will be returned in the order they were present in the original array.
Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.
If you aren't sure how many random items will be selected or how many items are in the array, then use min($yourNumberOfRandomItemsToReturn, count($yourArray))
.