3

Say I have the following array:

$var = array( 
"green" => array("one", "two"), 
"red" => array("three", "four"),
"yellow" => array("five", "six")
);

What code would I need to write to generate a random output of any of the numbers?

I've tried the following, which will give me either "one", "three" or "five".

$section = array_rand($var);
echo $var[$section][0];

However I can't seem to randomise the key, so it will randomly choose a colour, and then randomly choose a number within that colour. I'm obviously having a dim moment. Can anyone enlighten me? Thanks.

0

2 Answers 2

11

The short way to get random element in that case:

$var = array( 
"green" => array("one", "two"), 
"red" => array("three", "four"),
"yellow" => array("five", "six")
);

$section = array_rand($var); //here yoy get random first of array(green or red or yellow)
echo $var[$section][array_rand($var[$section])]; //here you get random element of this array
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, nicely explained as well.
Hope it will be usefull)
8

array_rand() will randomize the complete array. This means it will

  • consume much entropy
  • Use quite a lot of CPU horsepower, if the array is large
  • create a copy of the array, using up RAM.

So I prefer

function getrandomelement($array) {
  $pos=rand(0,sizeof($array)-1);
  $res=$array[$pos];
  if (is_array($res)) return getrandomelement($res);
  else return $res;
}

and ofcourse

echo getrandomelement($var);

EDIT

In case this is not clear, the above function will work for any dimension, even with different sizes (non-square/cube).

5 Comments

Wonderful solution! (Love the recursivity.)
This doesn't work with the above array, it only works when it has keys. How could this be adapted to work with values for keys as well?
Adaption is $res=$array[array_keys[$pos]]; inside the function
I couldn't get the above to work, as when I tried $res=$array[array_keys($pos)] I got an error relating to $pos being an integer and not an array. However I've adapted what I was doing a little and so it has still been useful. Thanks.
@Whitenoise It should be array_keys($array)[$pos]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.