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

0

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

how do we show a just one result that is random?
4

Complex? Are we on the same manual page?

$rand_key = array_rand($input, 1);

4 Comments

No the examples on php.net were over the top for what I wanted when all I wanted was something simple.
@Cameron that's intended: That is the array key. Use $input[$rand_key] to access the element
If 0 is the selected random key, it is the selected random key. Whats the matter with that?
Would it be possible to make sure a different value is shown each time? So almost rotating them but in a random order.
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.

Comments

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

Comments

2

Just a single function: array_rand().

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

3 Comments

The example above by waiwai933 doesn't have the 1 but outputs the same as your code. what does the 1 do?
@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.
The 1 as second argument is the default value, so you can omit it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.