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

4
  • 3
    Did you read the documentation of array_rand? what you want is $yourArray[array_rand($yourArray)]; Commented Jul 18, 2013 at 15:44
  • dup stackoverflow.com/questions/6355154/… Commented Jul 18, 2013 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 Commented Jul 18, 2013 at 15:49
  • THere's lots of dupes, that first isn't one. This is more to the point. 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. Commented Jul 18, 2013 at 17:58

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.