Home » Php » Simple PHP random array

Simple PHP random array

Posted by: admin July 12, 2020 Leave a comment


I have a simple array like this:

$input = array('Line1', 'Line2', 'Line3');

And want to echo one of the values randomly. I’ve done this before but can’t remember how I did it and all the examples of array_rand seem more complex that what I need.

Can any help? Thanks

How to&Answers:
echo $input[array_rand($input)];

array_rand() returns the key, so we need to plug it back into $input to get the value.


Complex? Are we on the same manual page?

$rand_key = array_rand($input, 1);


You could use shuffle() and then just pick the first element.

echo $input[0];

But I would go with the array_rand() method.


array_rand will help you select a random key of an array. From there you can get the value.

$randKey = array_rand($input);
echo $input[$randKey];


Just a single function: array_rand().

echo $input[array_rand($input,1)];