Wednesday, January 27, 2010

PHP: array_rand does not shuffle!

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 (=> 'key 5''key after 5'=> 'key 3''a' => 'key a'=> 'key 1'=> 'key 0''key after 0',);
print_r($a);
print_r(array_rand($a5));
print_r(array_rand($acount($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).

2 comments:

  1. experiencing the very same phenomenon ... on my local servers php, as well as on the ( different ) remote server's php.

    I guess this is a bug, right ?

    GreeZ,
    lab5

    ReplyDelete
  2. Hi lab5, thanks for your comment.
    Actually 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

    ReplyDelete