Simple random PHP array

I have a simple array:

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

And I want one of the values ​​to be chosen randomly. I have done this before, but I can’t remember how I did it, and all the array_rand examples seem to be the more complex that I need.

Can any help be given? Thanks

+7
arrays php
source share
5 answers
 echo $input[array_rand($input)]; 

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

+18
source share

Complex? Are we on the same page?

 $rand_key = array_rand($input, 1); 
+4
source share

You can use shuffle () and then just select the first element.

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

But I would go with the array_rand () method.

+3
source share

array_rand will help you choose a random array key. From there you can get the value.

 $randKey = array_rand($input); echo $input[$randKey]; 
+2
source share

Only one function: array_rand () .

 echo $input[array_rand($input,1)]; 
+2
source share

All Articles