7

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

Cameron
  • 27,963
  • 100
  • 281
  • 483

5 Answers5

18
echo $input[array_rand($input)];

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

waiwai933
  • 14,133
  • 21
  • 62
  • 86
4

Complex? Are we on the same manual page?

$rand_key = array_rand($input, 1);
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 1
    No the examples on php.net were over the top for what I wanted when all I wanted was something simple. – Cameron Nov 22 '10 at 00:34
  • @Cameron that's intended: That is the array key. Use `$input[$rand_key]` to access the element – Pekka Nov 22 '10 at 00:36
  • If *0* is the selected random key, it is the selected random key. Whats the matter with that? – KingCrunch Nov 22 '10 at 00:36
  • Would it be possible to make sure a different value is shown each time? So almost rotating them but in a random order. – Cameron Nov 22 '10 at 00:56
3

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.

Michael
  • 2,631
  • 2
  • 24
  • 40
2

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];
Ben Rowe
  • 28,406
  • 6
  • 55
  • 75
2

Just a single function: array_rand().

echo $input[array_rand($input,1)];
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • The example above by waiwai933 doesn't have the 1 but outputs the same as your code. what does the 1 do? – Cameron Nov 22 '10 at 00:37
  • @Cameron look into the manual. `If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.` – Pekka Nov 22 '10 at 00:37
  • The *1* as second argument is the default value, so you can omit it. – KingCrunch Nov 22 '10 at 00:40