wrap() and random()

Guarantee a value is an array, or pick a random element.

Syntax\Illuminate\Support\Arr::wrap($value);

The Arr::wrap() method wraps any value in an array if it is not one already (and leaves null as an empty array). It is handy when a function may receive one item or many. Arr::random() returns a random value from an array.

Example

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

When to use it

  • A notification service calls Arr::wrap() on a channel argument that may be either a string 'mail' or an array ['mail', 'sms'], ensuring the downstream loop always receives an array.
  • A middleware stack builder wraps the result of a config read with Arr::wrap() so a single middleware name and a list of names are handled by identical code.
  • A validation helper uses Arr::wrap() on rule definitions that can be either a string 'required|email' or an array ['required', 'email'] to normalise input.

More examples

Wrap a scalar into an array

Arr::wrap() always returns an array: scalars are wrapped, arrays pass through unchanged, and null becomes an empty array.

Example · php
use Illuminate\Support\Arr;

Arr::wrap('hello');     // => ['hello']
Arr::wrap(['a', 'b']); // => ['a', 'b']  (unchanged)
Arr::wrap(null);       // => []           (null becomes empty array)

Normalise a channel config value

Wrapping the config value means the foreach always works correctly regardless of whether the config holds a string or an array.

Example · php
use Illuminate\Support\Arr;

// config value may be a string or array
$channels = config('notifications.channels'); // 'mail' OR ['mail','sms']

// After wrap(), always iterate the same way
foreach (Arr::wrap($channels) as $channel) {
    Notification::route($channel, $recipient)->notify($notice);
}

Combine wrap and only for safe input

Pairs Arr::wrap() with Arr::only() so a function accepting a string or array of role names always produces a consistent output.

Example · php
use Illuminate\Support\Arr;

function resolveRoles(string|array $roles): array
{
    return Arr::only(
        ['admin' => 1, 'editor' => 2, 'viewer' => 3],
        Arr::wrap($roles)
    );
}

resolveRoles('admin');           // ['admin' => 1]
resolveRoles(['admin','viewer']); // ['admin' => 1, 'viewer' => 3]

Discussion

  • Be the first to comment on this lesson.