PHP: Get A Random Item From An Array

In PHP it’s easy to work with arrays. Just declare someting like this:

<?php
$arrX = array("Kay", "Joe","Susan", "Frank");
?>

Now you can access the values with their index (which starts a 0 for the first item).

<?php
// output "Kay"
echo $arrX[0];
 
// output "Susan"
echo $arrX[2];
?>

PHP offers you several ways to get a random value of the array. One simple way is by using the array_rand() function. array_rand() expects the array as a parameter and returns a random index value as integer which then can be used to get the array value.

<?php
// the array
$arrX = array("Kay", "Joe","Susan", "Frank");
 
// get random index from array $arrX
$randIndex = array_rand($arrX);
 
// output the value for the random index
echo $arrX[$randIndex];
?>

You can use the array_rand() function to get more than one random index. Just pass an integer value as second parameter to the function. Now it will return an array of indexes.

<?php
// the array
$arrX = array("Kay", "Joe","Susan", "Frank");
 
// get 2 random indexes from array $arrX
$randIndex = array_rand($arrX, 2);
 
/*
* output the value for the first random index
* you can access the first index with $randIndex[0]
* (may be a bit confusing for programming beginners)
*/
echo $arrX[$randIndex[0]];
/*
* output the value for the secondrandom index
*/
echo $arrX[$randIndex[1]];
?>

Be sure to pass a number less than the number of array elements as second parameter or otherwise PHP will give you an E_WARNING Error.

(Visited 11,125 times, 22 visits today)

Leave a Comment