get a random element from an array in php

To get a random element from an array in PHP, you can use the array_rand() function. This function returns a random key from the array, which you can then use to access the corresponding element.

Here's an example:

main.php
$myArray = ['apple', 'banana', 'orange', 'grape'];

$randomKey = array_rand($myArray);
$randomElement = $myArray[$randomKey];

echo $randomElement; // Outputs a random element from the array
191 chars
7 lines

In this example, we first define an array called $myArray containing several fruit names. We then use the array_rand() function to generate a random key from the array, which we assign to $randomKey. Finally, we use this key to access the corresponding element in the array ($myArray[$randomKey]), which we assign to $randomElement. We can then do whatever we want with the random element, such as print it to the screen.

related categories

gistlibby LogSnag