Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to get a random value with php function *array_rand*.

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";

How to can I get value from this? Like a $input[$rand_keys];

Thanks in advance.

share|improve this question
 
You mean how you get the names? Don't you get 2 random names from the array with the above code? Like here php.net/manual/en/function.array-rand.php –  Robin V. Aug 4 '13 at 19:19
 
Sounds like he's looking for a way to get a bunch of array values at once, given a bunch of keys. –  cHao Aug 4 '13 at 19:23
 
Give some more details on what you mean by $input[$rand_keys] -- what kind of result are you trying to get? –  GreatBigBore Aug 4 '13 at 19:24
add comment

3 Answers

You are using it correctly. array_rand returns a set of keys for random entries of your array. In your case, though, if you want to pick all entries in a randomized fashion you should be using:

$rand_keys = array_rand($input, 5);

If you want an array out of this, you could just do $rand_values = array($input[$rand_keys[0]], $input[$rand_keys[1]], $input[$rand_keys[2]], $input[$rand_keys[3]], $input[$rand_keys[4]]);.

share|improve this answer
add comment

I haven't seen a built-in way yet. I tend to do something like this:

$rand_values = array_map(
    function($key) use ($input) { return $input[$key]; },
    $rand_keys
);

But that's because i thoroughly detest repeating myself. :P

share|improve this answer
add comment

So many ways to do it, including simple loops... Here's probably the most compact one-liner:

$randValues = array_intersect_key($input, array_flip(array_rand($input, 2)));
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.