tags:

views:

65

answers:

4

How could I echo 5 elements randomly from an array of about 20?

Thanks.

+6  A: 

array_rand

SilentGhost
A: 
for($i=0; $i++; $i < 5)
{
    echo $array[rand(0, count($array)-1);
}

or

for($i=0; $i++; $i < 5)
{
    echo array_rand($array);
}

or

array_map("echo", array_rand($array, 5));
njk
There is a change here that you would pick the same element more than once, which is probably not what the OP wants.
Neil Aitken
The point of array_map is to *create a new array* by applying a function to each item of an existing array. If all you want to do is apply the function, use array_walk.
bish
+1  A: 

Does this work?

$values = array_rand($input, 5);

Or, as a more flexible function

function randomValues($input, $num = 5) {
    return array_rand($input, $num);
}

//usage
$array = range('a', 'z');

//prints 5 random characters from the alphabet
print_R(randomValues($array));
davethegr8
A: 

$n = number of random numbers to return in the array

$min = minimum number

$max = maximum number

function uniqueRand($n, $min = 0, $max = null)
{
    if($max === null)
    $max = getrandmax();
   $array = range($min, $max);
   $return = array();
   $keys = array_rand($array, $n);
   foreach($keys as $key)
       $return[] = $array[$key];
   return $return;
}

$randNums = uniqueRand(5, 0, count($array)-1);
for($i=0; $i++; $i < 5)
{
    echo $array[$randNums[i]);
}
CJ