Page 1 of 1

array_rand problem

Posted: Tue Dec 22, 2009 10:47 pm
by someguyhere
This works fine:

Code: Select all

    $rand_keys = array_rand($spin, 2);
    echo $spin[$rand_keys[0]];
    echo $spin[$rand_keys[1]];
But this doesn't:

Code: Select all

    $rand_keys = array_rand($spin, 1);
    echo $spin[$rand_keys[0]];
Any idea why?

Re: array_rand problem

Posted: Tue Dec 22, 2009 11:33 pm
by iamngk
If you look into PHP manual, you will find the below description for returning value by this function.
Return Values
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
.

So when you are getting one value, you will not get the array i.e. you will get the key value.

Code: Select all

$rand_keys = array_rand($spin, 1);
    echo $spin[$rand_keys];