tags:

views:

579

answers:

4

I need to be able to pull a random value out of my array, let's assume i have array with 100 values, how can i pull randomly 5 values out of this array?

A: 

actually I just found array_rand(); maybe that?

alexus
+6  A: 

Try this:

$data = range(1, 100);

$results = array_rand($data, 5);
print_r($results);
fuentesjr
+1  A: 

You are correct.

according to http://us3.php.net/manual/en/function.array-rand.php

you can do:

<?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";
?>
nsr81
+1  A: 

with array_rand(), produced array will always be ordered

$results[0] < $results[1] < $results[2] < $results[3] < $results[4]

if you want it to be unordered, after array_rand(), you can use shuffle() function

$data = range(1, 100);
$results = array_rand($data, 5);
shuffle($result);
print_r($results);
H2O