Asim Zaidi
Asim Zaidi

Reputation: 28344

php random array

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

Upvotes: 0

Views: 1037

Answers (3)

dev-null-dweller
dev-null-dweller

Reputation: 29492

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
 )
 */

Upvotes: 0

Fivell
Fivell

Reputation: 11929

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.

Upvotes: 0

Samir Talwar
Samir Talwar

Reputation: 14330

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.

Upvotes: 2

Related Questions