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.php191 chars7 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.
gistlibby LogSnag