PHP function array_rand() does not shuffle results anymore and behaves like array_keys() in some circumstances.
Yes, that is correct. The function array_rand() gets random key (or keys) from given array. Funny thing is that it does not shuffle the keys anymore. So the following code:
<?php
$a = array (5 => 'key 5', 'key after 5', 3 => 'key 3', 'a' => 'key a', 1 => 'key 1', 0 => 'key 0', 'key after 0',);
print_r($a);
print_r(array_rand($a, 5));
print_r(array_rand($a, count($a));
print_r(array_keys($a);
?>
would produce that result:
Array ( [5] => key 5 [6] => key after 5 [3] => key 3 [a] => key a [1] => key 1 [0] => key 0 [7] => key after 0 ) Array ( [0] => 3 [1] => a [2] => 1 [3] => 0 [4] => 7 ) Array ( [0] => 5 [1] => 6 [2] => 3 [3] => a [4] => 1 [5] => 0 [6] => 7 ) Array ( [0] => 5 [1] => 6 [2] => 3 [3] => a [4] => 1 [5] => 0 [6] => 7 )
That means, that getting randomly array-size number of keys from the array array_rand($a, count($a)) give exactly same result as getting all the keys in order array_keys($a).
experiencing the very same phenomenon ... on my local servers php, as well as on the ( different ) remote server's php.
ReplyDeleteI guess this is a bug, right ?
GreeZ,
lab5
Hi lab5, thanks for your comment.
ReplyDeleteActually it is not a bug. It was mentioned on array_rand() manual page in the changelog section:
5.2.10 The resulting array of keys is no longer shuffled.
Cheers,
Jacek
Excellent post! Your post is very useful and I felt quite interesting reading it. Expecting more post like this. Thanks for posting such a good post. laptop service in home. To service your laptop with offer prices, Please visit : Laptop service center in Navalur
ReplyDelete