Fast way to randomly choose an Array item

When dealing with arrays in PHP, I usually need to choose a random item to display, for example an image that rotates randomly in a homepage or interior page, actually doesn’t matter which page.

The applications and needs may differ a lot, but here is a simple snippet that you can use to randomly select an item in a PHP Array.

Basically it uses array_rand() function.

For example, imagine we have the filenames for images that we want to rotate in a page (banners or whatever). Then I’ll define an array, and then I will use array_rand() to get a random key.


$headers = array("menu_header_1.jpg", "menu_header_2.jpg", "menu_header_3.jpg", "menu_header_4.jpg");
$value = $headers[array_rand($headers)];

Leave a Reply