Home » Php » Simple PHP random array

Simple PHP random array

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

Answer:

Complex? Are we on the same manual page?

$rand_key = array_rand($input, 1);

Answer:

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

shuffle($input);
echo $input[0];

But I would go with the array_rand() method.

Answer:

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];

Answer:

Just a single function: array_rand().

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