Backend Development 2 min read

array_rand(): Randomly Retrieve One or More Elements from an Array

This article explains PHP’s array_rand() function, detailing its purpose of selecting one or multiple random keys from an array, describing its parameters, return values, error handling, and provides a complete code example demonstrating how to retrieve and display random elements.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
array_rand(): Randomly Retrieve One or More Elements from an Array

PHP provides the array_rand() function to select one or more random keys from an array.

Parameters

input : the array from which to pick.

num_req : the number of keys to retrieve; if it exceeds the array size, a warning is generated.

Return value

If a single key is requested, array_rand() returns that key as a scalar; otherwise it returns an array of random keys, allowing you to access the corresponding values.

Example

The output might be:

Morpheus
Trinity
phprandom selectionphp-functionsarray_rand
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.