array_rand problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

array_rand problem

Post 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?
iamngk
Forum Commoner
Posts: 50
Joined: Mon Jun 29, 2009 2:20 am

Re: array_rand problem

Post 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];
Post Reply