1

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.

3
  • 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 Commented Aug 4, 2013 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. Commented Aug 4, 2013 at 19:23
  • Give some more details on what you mean by $input[$rand_keys] -- what kind of result are you trying to get? Commented Aug 4, 2013 at 19:24

4 Answers 4

2

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)));
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, this is working fine for limit > 1.. but it's not working when i give the limit to 1.. it's displaying warnings as:: array_flip() expects parameter 1 to be array and ` array_intersect_key(): Argument #2 is not an array` ...... do u have any solution for that..
If you just need 1, then just do $input[array_rand($input)]. The return value of array_rand is very different for 1 and >1.
1

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

Comments

0

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

Comments

0

Change: $rand_keys = array_rand($input, 2); to $rand_keys = array_rand($input, 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.