Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My code randomizes an array index which consists 3 values for example.

$t1 = array("6","7","8");    
$randomized = array_rand($t1, 3);
echo $t1[$randomized[0]]; 

only outputs the value 6.

$randomized = array_rand($t1, 2);
echo $t1[$randomized[0]];

only outputs the value 6 or 7.

However this works :

    $randomized = array_rand($t1, 1);
    echo $t1[$randomized]; 

this works and outputs 6,7 or 8

I don't get it and YES I did execute the function like 10 times to see if its not just coincidence.

share|improve this question
add comment

2 Answers

This is not a bug.

Since 5.2.10, PHP no longer shuffles the extracted keys, they're always ordered.

Because of this ordering, extracting 2 keys from an array comprising 4 values can be done in only 6 ways:

4! / (2! * 2!)

This is contrary to your expected 12:

4! / 2!

Therefore, extracting all keys out of the array can only be done in one way and thus effectively yields array_keys($array);

My advice would be to use shuffle() instead.

share|improve this answer
    
+1. This makes more sense. And shuffle() sounds like the correct tool for this purpose. –  Amal Murali Nov 24 '13 at 9:34
add comment

array_rand() according to the documentation...

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

There is no mention in the documentation that it randomizes the order of the randomly chosen keys. What you apparently want is shuffle().

So try something like this:

$t1 = array("6","7","8");
$randomized = array_rand($t1, 3);
shuffle($randomized);
echo $t1[$randomized[0]]; 
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.