2

So I have this array of objects. From which I want to take at random one of the objects from the array, and use it for its intended purpose. I have tried array_rand() but that only returned a random value from one of the arrays within. Is there a method similar to array_rand() that will let me use the whole array as the variable rather than a value pluked from within it?

Example Array:

Array
(
    [0] => stdClass Object
        (
            [id] => 10003
            [state] => CA
        )

    [1] => stdClass Object
        (
            [id] => 10003
            [state] => CA
        )

    [2] => stdClass Object
        (
            [id] => 10006
            [state] => CA
        )
)

What I want to do when doing something similar to array_rand() is end up with a variable that is

[0] => stdClass Object
            (
                [id] => 10006
                [state] => CA
            )

or similar

chris
  • 36,115
  • 52
  • 143
  • 252
  • 3
    Did you read the documentation of `array_rand`? what you want is `$yourArray[array_rand($yourArray)];` – Mahn Jul 18 '13 at 15:44
  • dup http://stackoverflow.com/questions/6355154/multi-dimensional-array-in-random-order – internals-in Jul 18 '13 at 15:47
  • 1
    @7-isnotbad I wouldn't say it's quite a duplicate. While there's a bunch of useful information in the question you've linked, shuffling the array might not be the best way of getting a single random value – StephenTG Jul 18 '13 at 15:49
  • THere's lots of dupes, that first isn't one. [This is more to the point](http://stackoverflow.com/questions/4233407/get-random-item-from-array/4233416#4233416). There's no difference in getting a random scalar from an array to getting a random complex variable, an array entry is an array entry, doesn't matter what it is. – Wrikken Jul 18 '13 at 17:58

1 Answers1

7

From array_rand documentation:

[array_rand] picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

To summarize: if you want to retrieve a random value from an array, you need to use the random key provided by array_rand to access it.

Solution, assuming your array is stored in $obj:

$random_obj = $obj[array_rand($obj));
jsalonen
  • 29,593
  • 15
  • 91
  • 109