Arr::random

Returns one random value from an array, or an array of several when a count is given.

Signature
public static function random($array, $number = null, $preserveKeys = false)

Parameters

ParameterTypeDescription
$$arrayarrayThe array to sample from.
$$numberoptionalint|null= nullHow many items to return. Passing any integer — including 1 — makes the return value an array.
$$preserveKeysoptionalbool= falseKeep the original keys on the returned items instead of reindexing from zero.

Return value

mixedA single random value when $number is null, otherwise an array of that many values.

Errors

Throws InvalidArgumentException when the requested count is larger than the number of items available.

Arr::random draws items without replacement using PHP's Random\Randomizer, so the same element is never returned twice within one call.

When to reach for it

  • Picking a featured item, a rotating testimonial or a random tip for a page.
  • Selecting a sample of records for a spot check or a seeded demo dataset.
  • Choosing a fallback avatar colour or placeholder from a fixed palette.

What trips people up

The return type changes with the second argument. With no count you get the value itself; with a count — even 1 — you get an array. Code written against Arr::random($a) breaks the moment someone adds a count, so treat these as two different calls.

Asking for more than exists throws. InvalidArgumentException is raised with the message "You requested N items, but there are only M items available." Clamp with min($n, count($array)) when the count is user-supplied.

Edge cases return quietly. An empty array gives null without a count and [] with one; a count of 0 or less gives [] rather than an error.

By default the returned array is reindexed from zero. Pass true as the third argument when you need to know which original positions were drawn.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Show a rotating featured product or testimonial on a landing page.
  • Take a random sample of rows for a manual quality check.
  • Pick a placeholder colour from a fixed palette for a generated avatar.

Frequently asked questions

Why does Arr::random return an array when I only asked for one item?

Because passing any count argument switches the return type to an array, including a count of 1. Omit the second argument entirely to get the bare value.

How do I stop Arr::random throwing when the array is smaller than my count?

Clamp the count with min($number, count($array)). The method deliberately throws InvalidArgumentException rather than returning fewer items than requested.

Is Arr::random cryptographically secure?

It uses PHP's Random\Randomizer with the default secure engine, so it is suitable for general use, but it cannot be seeded — pin or sort the output if you need a reproducible test.

More examples

Edge cases and the exception

Note the asymmetry: an empty source is tolerated in both forms, but an oversized request is not. min() against count() is the standard guard when the number comes from a query string or config value.

Example · php
<?php

use Illuminate\Support\Arr;

$array = ['a', 'b', 'c'];

// Empty array: null without a count, [] with one.
var_dump(Arr::random([]));
var_dump(Arr::random([], 2));

// Zero or fewer returns an empty array rather than throwing.
var_dump(Arr::random($array, 0));

// Requesting more than exists throws.
try {
    Arr::random($array, 10);
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), PHP_EOL;
}

// Clamp when the count comes from the outside.
$requested = 10;
echo count(Arr::random($array, min($requested, count($array)))), PHP_EOL;

/*
NULL
array(0) {
}
array(0) {
}
You requested 10 items, but there are only 3 items available.
3
*/

Preserving keys to know what was drawn

The first call reindexes to 0 and 1, discarding the plan names that identify each row. The third argument keeps them, which is essential whenever the key carries meaning rather than just position. The specific plans shown vary per run.

Example · php
<?php

use Illuminate\Support\Arr;

$plans = [
    'free' => ['seats' => 1],
    'team' => ['seats' => 10],
    'business' => ['seats' => 50],
    'enterprise' => ['seats' => 500],
];

// Without preserveKeys the plan names are lost.
$sample = Arr::random($plans, 2);
echo implode(',', array_keys($sample)), PHP_EOL; // 0,1

// With preserveKeys the plan names survive.
$named = Arr::random($plans, 2, true);

foreach ($named as $name => $plan) {
    echo $name, ' => ', $plan['seats'], PHP_EOL;
}

// e.g.
// 0,1
// team => 10
// enterprise => 500

Discussion

  • Be the first to comment on this lesson.