Sometimes you need to select a random element from a PHP array. For example, you might want to display a random product, choose a quiz question, or feature a different article each time a page loads.
The array_rand() function lets you select one or more random array keys without modifying the original array.
What Is array_rand() in PHP?
The array_rand() function randomly selects one or more keys from an array.
Its syntax is:
array_rand(
array $array,
int $num = 1
): int|string|array
The parameters are:
$array— The array to select from. It must not be empty.$num— The number of keys to select. The default is1.
The return value depends on how many keys you request:
- One key: Returns an integer or string.
- Multiple keys: Returns an array containing the selected keys.
Important: The function returns array keys, not their corresponding values.
Example 1: Selecting One Random Element
Let's choose a random programming language from an indexed array.
<?php
$languages = [
"PHP",
"Python",
"JavaScript",
"Go"
];
$key = array_rand($languages);
echo $languages[$key];
Possible output:
Python
The result may differ each time the script runs.
First, array_rand() selects a random key. Then, $languages[$key] retrieves the value stored under that key.
Example 2: Selecting Multiple Random Elements
You can provide a second argument to select several keys at once.
<?php
$colors = [
"Red",
"Green",
"Blue",
"Yellow",
"Purple"
];
$keys = array_rand($colors, 3);
foreach ($keys as $key) {
echo $colors[$key] . PHP_EOL;
}
Possible output:
Red
Blue
Purple
PHP selects three different keys, so the same array entry is never selected twice in a single call.
There is one important detail: when multiple keys are returned, they follow their original order in the input array, not a newly shuffled order.
Also, requesting exactly one key still returns a single integer or string, not an array.
Example 3: Working with Associative Arrays
The function works with associative arrays containing named keys.
<?php
$products = [
"KB-101" => "Keyboard",
"MS-102" => "Mouse",
"MN-103" => "Monitor"
];
$productId = array_rand($products);
echo "ID: " . $productId . PHP_EOL;
echo "Product: " . $products[$productId];
Possible output:
ID: MS-102
Product: Mouse
Because the array uses product IDs as keys, array_rand() returns one of those IDs.
This is useful when you need both the identifier and the value of a randomly selected record.
Practical Example: Displaying a Random Featured Product
Imagine you're building an online store and want to display one random product that is currently available.
We'll first filter out products with no stock, then randomly select a product from the remaining entries.
Create a file named featured-product.php:
<?php
declare(strict_types=1);
$products = [
"KB-101" => [
"name" => "Keyboard",
"stock" => 12
],
"MS-102" => [
"name" => "Mouse",
"stock" => 0
],
"MN-103" => [
"name" => "Monitor",
"stock" => 5
],
"WC-104" => [
"name" => "Webcam",
"stock" => 8
]
];
// Keep products with available stock.
$available = array_filter(
$products,
static fn(array $product): bool =>
$product["stock"] > 0
);
// Select a random available product.
if ($available !== []) {
$productId = array_rand($available);
$product = $available[$productId];
$message = $product["name"]
. " - "
. $product["stock"]
. " in stock";
echo "<h2>Featured Product</h2>";
echo "<p>" . htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
) . "</p>";
} else {
echo "<p>No products available.</p>";
}
Possible browser output:
Featured Product
Monitor - 5 in stock
The Mouse is excluded because its stock quantity is zero. The function randomly selects one of the remaining products.
Checking that $available is not empty prevents an exception when no products qualify.
This pattern also works for random articles, recommendations, and quiz questions.
Handling Empty Arrays and Invalid Counts
The $num argument must be greater than zero and must not exceed the number of elements in the array.
In PHP 8+, an empty input array or an invalid count causes a ValueError.
<?php
$items = ["PHP", "Python"];
try {
$keys = array_rand($items, 5);
} catch (ValueError $error) {
echo "Invalid number of random selections.";
}
Output:
Invalid number of random selections.
When the selection count is dynamic, validate it before calling the function:
$count = 2;
if ($count >= 1 && $count <= count($items)) {
$keys = array_rand($items, $count);
}
Is array_rand() Suitable for Security-Sensitive Operations?
No. array_rand() is designed for general-purpose random selection and does not provide cryptographically secure randomness.
Do not use it to select security tokens, generate passwords, or make security-sensitive random decisions.
For cryptographically secure selection, PHP 8.2+ provides Random/Randomizer with the Random/Engine/Secure engine.
The PHP documentation recommends the Randomizer API for newly written code.
array_rand() vs Related Functions
| Function | Purpose |
|---|---|
array_rand() |
Selects one or more random array keys. |
shuffle() |
Randomizes the order of array elements, modifying the array. |
Random/Randomizer::pickArrayKeys() |
Selects random keys using a configurable random engine (PHP 8.2+). |
Choose array_rand() when you need random keys without changing the source array. Use shuffle() when you need to rearrange the entire collection.
Key Takeaways
array_rand()selects one or more random keys from an array.- It returns a single key when selecting one element and an array of keys when selecting multiple elements.
- Use the returned keys to retrieve their associated values.
- Multiple selections contain distinct keys and are returned in the original array order.
- Empty arrays and invalid selection counts throw a
ValueErrorin PHP 8+. - The function does not modify the original array and is not cryptographically secure.
The array_rand() function provides a convenient way to select random entries from PHP arrays. It is especially useful for featured content, random recommendations, and other situations where you need occasional random selections.
For additional details, see the official PHP array_rand() documentation.