usertest
usertest

Reputation: 27648

Output array elements randomly with PHP

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

Thanks.

Upvotes: 0

Views: 927

Answers (3)

CJ.
CJ.

Reputation: 1044

$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]);
}

Upvotes: 0

davethegr8
davethegr8

Reputation: 11605

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

Upvotes: 1

nicolaskruchten
nicolaskruchten

Reputation: 27440

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

Upvotes: 0

Related Questions