Snickerson
Snickerson

Reputation: 21

PHP: array_rand random value

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.

Upvotes: 1

Views: 6864

Answers (4)

continum4
continum4

Reputation: 1

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

Upvotes: 0

deceze
deceze

Reputation: 522081

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

Upvotes: 2

cHao
cHao

Reputation: 86505

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

Upvotes: 1

federicot
federicot

Reputation: 12341

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

Upvotes: 0

Related Questions