tags:

views:

146

answers:

3

I am trying to get a random array like this

srand((float) microtime() * 10000000);
$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";

it shows 2 numbers randomly if I have $rand_keys = array_rand($input, 2);$rand_keys = array_rand($input, 5); but since I want all 5 to show it doesnt work. whats causing that. I need to use array_rand. thanks

+1  A: 

array_rand sorts the keys in the same order they exist in the original array. If you want a shuffled array, use the shuffle function first:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
shuffle($input);
$rand_keys = array_rand($input, 5);
for ($i = 0; $i < count($rand_keys); $i++) {
    echo $input[$rand_keys[$i]] . "\n";
}

Of course, in the case where you access all five, there's no need to call array_rand at all, but if you're varying its second parameter, this will still work.

As an aside, calling the srand function is unnecessary—it's done for you as of PHP 4.2.

Samir Talwar
please read above carefully. I dont wanna use shuffle or I wouldnt be asking question
@user295189: Why don't you want to use `shuffle`?
Samir Talwar
A: 

changelog of this function :

5.2.10   The resulting array of keys is no longer shuffled.

this function doesn't return elements in random order, it returns random elements. So if you want to get 5 random elements from your array, it just gets you all elements.

Fivell
A: 

I assume you don't want use shuffle on original array, because it rearranges keys? If so, then just shuffle array with random keys, leaving input array unchanged.

$rand_keys = array_rand($input, 5);
shuffle($rand_keys);
print_r($rand_keys);
/**
 * Sample output
 Array
 (
    [0] => 0
    [1] => 1
    [2] => 4
    [3] => 2
    [4] => 3
 )
 */
dev-null-dweller