Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose 3 different random values from an array

Tags:

arrays

php

random

I have an array of 30 values and I need to extract from this array 3 different random values. How can I do it?

like image 796
markzzz Avatar asked Oct 15 '10 20:10

markzzz


People also ask

How do you select a random value from an array in Python?

Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.

How do you randomly select an element from an array in C?

What you propose is the best solution there is - choose a random index and then use the element at this index. If your question is how to get a random integer, use the built-in function rand() .

Can we access elements randomly in an array?

Random(direct) access implies the ability to access any entry in a array in constant time (independent of its position in the array and of array's size). And that is big advantage. It is typically contrasted to sequential access.


3 Answers

I'm not sure why bother using array_rand() at all as it's just an extra function call for seemingly no reason. Simply shuffle() and slice the first three elements:

shuffle($array);
print_r(array_slice($array, 0, 3));
like image 70
Eaten by a Grue Avatar answered Oct 06 '22 00:10

Eaten by a Grue


Shamelessly stolen from the PHP manual:

<?php
$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";
?>

http://us2.php.net/array_rand

Note that, as of PHP 5.2.10, you may want to shuffle (randomize) the keys that are returned via shuffle($rand_keys), otherwise they will always be in order (smallest index first). That is, in the above example, you could get "Neo, Trinity" but never "Trinity, Neo."

If the order of the random elements is not important, then the above code is sufficient.

like image 36
Matthew Avatar answered Oct 05 '22 23:10

Matthew


use shuffle($array) then array_rand($array,3)

like image 20
Sabeen Malik Avatar answered Oct 05 '22 23:10

Sabeen Malik