PHP Array: loop through an array and choose a random element

PHP Array: loop through an array and choose a random element?

PHP makes it simple to loop through array components using the mt_rand() function, and just needs the code shown below:

 
// An example array 
$exampleArray = array("apple", "banana", "cherry", "date", "elderberry"); 

// Using the count() function to get the number of elements in the array 
$arrayLength = count($exampleArray); 

// Generating a random number between 0 and the number of elements in the array 
$randomIndex = mt_rand(0, $arrayLength - 1); 

// Using the random index to access a random element in the array 
$randomElement = $exampleArray[$randomIndex]; // Outputting the random element echo $randomElement; ?>

There is also another method with shuffle() function:

 
shuffle($exampleArray); 
echo $exampleArray[0]; 
?>

If you find this solution useful, please share this link!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Disclaimer:

As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.