This question already has an answer here:
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
</div>
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));