PHP array_rand() Function: Usage & Examples

The array_rand() is a helper function in PHP that makes it easier when dealing with arrays; you can just pull out random items from arrays without giving yourself a headache. Think of it like a lucky dip—you reach in, pull out something, and voilà: you have your random value(s) from the array, ready to use.

What is “array_rand()”? Syntax and Definition

The function array_rand() returns one or more random keys from a given array. Put this another way: assume you have an array containing a list of colors; if you need a single color, that’s quite straightforward—pass the array to array_rand(), and it returns one random key within that array. If you want more than one random item, just tell array_rand() how many, and it will return an array of random keys. 

Here is the basic syntax for array_rand():

array_rand(array $array, int $num = 1): int|string|array
  • $array: The array you’re picking from.
  • $num: The number of random keys you want. It’s optional; if you skip it, array_rand() just assumes you want one.

How Does It Work?

Under the hood, array_rand() is rather uncomplicated. Suppose you pass in an array of movie genres: ['Action', 'Comedy', 'Drama', 'Sci-Fi']. When you execute array_rand($array), it returns one key. That key points to a random genre in your list. It’s not returning the value directly, just the key, so if you want the actual genre, you must access it like $array[$randomKey].

For more than one element, it works the same but returns an array of random keys. Let’s look at a few examples to make this clear.

Examples

Example 1: Obtaining a Single Random Value.

$colors = ['red', 'blue', 'green', 'yellow'];
$randomKey = array_rand($colors);
echo $colors[$randomKey]; // Outputs a random color

Example 2: Generating Multiple Random Values

$colors = ['red', 'blue', 'green', 'yellow'];
$randomKeys = array_rand($colors, 2);

foreach ($randomKeys as $key) {
    echo $colors[$key] . " ";
}
// Outputs two random colors

The first example selects a single random key with array_rand($colors) from the $colors array, and we use $colors[$randomKey] to get and display that colour.

The second example makes use of array_rand($colors, 2) to select two random keys, which are stored in $randomKeys. A foreach loop then accesses each of the selected keys to print two random colours from the array. The following are the advantages of this method: fast and convenient to draw one or many random items out of an array without shuffling – changing – the original array.

Similar Reads

PHP $_SESSION: Secure Your Web Applications in PHP

It’s very important to remember user data for each session when building web applications. This enables a high level of…

Learn How to Insert Documents in MongoDB Using PHP

Inserting documents into your MongoDB collections is one of the most basic but important tasks when working with PHP. In…

PHP Spaceship Operator

If you are new to the PHP Spaceship Operator, then let me tell you, you're in for a treat. This…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

PHP Escape Characters: How to Escape Special Characters

Escape characters appeared in PHP because some symbols in strings serve special purposes. For example, a quote can end a…

PHP Loop: How Loops Work with Examples

A loop in PHP helps you run tasks without repeating the same lines. In this article, you will learn how…

PHP array_find_key: How it Works with Examples

The PHP array_find_key function finds a key in an array by a condition. It checks each element and returns the…

PHP Object | How to Create an Instance of a Class

The PHP object is an instance from the PHP class or the main data structure that is already been created…

PHP str_repeat: How it Works with Examples

PHP gives you many string tools. One of them is php str_repeat. This function repeats a texts as many times…

History of PHP: From PHP/FI to Modern Web Development

You use PHP every day if you build websites, but most people do not know where it came from or…

Previous Article

PHP fopen: Understanding fopen Modes

Next Article

PHP array_pop: Remove and Return the Last Element of an Array

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.