PHP · TUTORIAL
How to Pick a Random Item from a PHP Array
Select one entry or several unique entries while handling array keys, empty lists and repeat choices.
Random selection is useful for a featured article, a rotating tip, or a set of recommended pages. The basic PHP code can be very short, but details matter: arrays may have named keys, the list may be empty, and “eight unique picks” is different from choosing eight times independently. A reliable implementation defines those behaviors before displaying a result.
The examples below use editorially maintained data rather than paths supplied by a visitor. Each recommendation keeps its title and URL together. That prevents a randomly selected title from becoming paired with the wrong destination, and it makes the result easier to validate and escape before inserting it into HTML.
The simplest choice returns a key
For an ordinary nonempty array, array_rand() chooses a random key. To obtain the value, use that key to index the original array. Do not assume the returned number is the value or that every array uses consecutive integer keys. PHP arrays can also use strings such as php and javascript as keys.
<?php
$topics = ['php' => 'PHP', 'js' => 'JavaScript', 'ai' => 'Artificial Intelligence'];
if ($topics === []) {
throw new RuntimeException('No topics are available.');
}
$key = array_rand($topics);
$topic = $topics[$key];
echo htmlspecialchars($topic, ENT_QUOTES, 'UTF-8');
An empty-list check is part of the example because a list populated from another file can be empty even when your first test data is not. For a public page, you might skip the recommendation section or show a curated fallback instead of throwing an exception. Choose that behavior explicitly rather than relying on a warning or an unexpected blank card.
Keep a complete recommendation in one entry
If the output needs a title, path, category, and image, put those fields in one array entry. Then select the whole entry. This structure scales better than maintaining several parallel arrays whose positions must remain synchronized. Adding a new recommendation becomes one edit instead of four matching edits.
<?php
$articles = [
['title' => 'Read a Text File', 'path' => '/programming/php/read-text-file/'],
['title' => 'Item of the Day', 'path' => '/programming/php/item-of-the-day/'],
];
$article = $articles[array_rand($articles)];
$href = htmlspecialchars($article['path'], ENT_QUOTES, 'UTF-8');
$title = htmlspecialchars($article['title'], ENT_QUOTES, 'UTF-8');
echo '<a href="' . $href . '">' . $title . '</a>';
These paths are controlled by the site owner. Escaping prevents their characters from becoming unintended HTML, but escaping alone does not make an arbitrary URL safe. If you accept destinations from untrusted data, validate their scheme and destination as well. A local allowlist is a useful approach for a small website.
Choose several unique entries
Calling the single-item example repeatedly can choose the same entry more than once. If you want a group of unique recommendations, ask for multiple keys in one call. The requested count must fit the available list. The return shape also depends on the count: one selected key is a scalar, whereas multiple selected keys are returned in an array.
<?php
$wanted = min(8, count($articles));
$recommendations = [];
if ($wanted > 0) {
$keys = (array) array_rand($articles, $wanted);
foreach ($keys as $key) {
$recommendations[] = $articles[$key];
}
shuffle($recommendations);
}
Casting the result to an array lets the loop work when there is only one eligible article. The selected keys identify distinct entries, but duplicate records already in your source data can still produce duplicate destinations. Remove duplicate paths when preparing the data if that distinction matters. The final shuffle gives the selected cards a randomized display order.
Exclude the current page before selecting
A recommendation for the page a visitor is already reading wastes a slot. Filter it out before selecting the count or calling array_rand(). If you remove it afterward, you can end up with fewer cards than intended. For a directory-based site, use a canonical path you already know from the page configuration instead of trusting an arbitrary incoming URL.
<?php
$currentPath = '/programming/php/read-text-file/';
$eligible = array_values(array_filter(
$articles,
static fn($article) => $article['path'] !== $currentPath
));
// Select from $eligible after checking that it is nonempty.
array_values() creates consecutive indexes after filtering. It is not necessary for array_rand() itself, but is useful if you later select by numerical position. Apply other rules here too, such as keeping recommendations within a category or removing unpublished pages. A random selection should still come from a relevant, valid pool.
When to use random_int() instead
For a security-sensitive random integer, use an appropriate secure source such as random_int(). To select by position, first turn the array into a zero-based list, verify it is nonempty, and request a number between zero and its last index. Do not treat an ordinary content-rotation function as a generator for passwords, reset tokens, or other secrets.
<?php
$values = array_values($eligible);
if ($values !== []) {
$selected = $values[random_int(0, count($values) - 1)];
}
Random does not automatically mean balanced
A uniform selection gives each entry an equal chance on each draw, but it does not guarantee that a small group of visitors will see every entry equally often. Repeat choices are normal. If your goal is to give each article a turn, use a rotation schedule or track which items have already appeared. If some entries should appear more often than others, that is a weighted-selection problem and needs an explicit weighting rule. Duplicating an entry in the list is an informal way to change its probability, but it also complicates the meaning of unique recommendations. Keep your selection rule distinct from your editorial priorities.
Decide how often the result should change
Random selection runs when PHP executes. A page cache may reuse the resulting HTML, so visitors might see the same choices until the cache expires. Conversely, an uncached page can change on every request. Neither behavior is inherently wrong; choose the one that suits the feature. For a predictable daily pick, use a date-based selection instead of a new random choice on every load.
Test an empty list, a one-entry list, named keys, duplicate destinations, and fewer than eight eligible entries. Keep the data structure clear and the selection rule visible. You can combine this technique with a text-file reader, or use the daily-item project when you want a schedule rather than randomness.
Reference: PHP array_rand() and PHP random_int().