"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you extract a random element from an array in PHP?

How do you extract a random element from an array in PHP?

Posted on 2025-02-28
Browse:301

How do you extract a random element from an array in PHP?

Random Selection from an Array

In PHP, obtaining a random item from an array can be accomplished with ease. Consider the following array:

$items = [523, 3452, 334, 31, 5346];

To retrieve a random item from this array, utilizing the array_rand() function is an effective solution:

echo $items[array_rand($items)];

The array_rand() function returns a random key from the array. By indexing the $items array with this key, we access a random element from the array. This approach provides a straightforward and robust method for selecting random items.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3