• support@answerspoint.com

How to get random value out of an array in php?

2238

I have a an array called $r_arr= array(1,2,3,4);

I need to get a random value out of this array and store it in a variable, how can I do this?

$my_arr= Array(523,3452,334,31,...5346);

Each item of this array is some number.

How do I get random item from $my_arr?

2Answer


0

You can also do just:

$k = array_rand($array);
$v = $array[$k];

This is the way to do it when you have an associative array.

  • answered 8 years ago
  • Sunny Solu

0

You can use mt_rand()

$random = $ran[mt_rand(0, count($ran) - 1)];

This comes in handy as a function as well if you need the value

function random_value($array, $default=null)
{
    $k = mt_rand(0, count($array) - 1);
    return isset($array[$k])? $array[$k]: $default;
}
  • answered 8 years ago
  • Sandy Hook

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2238 times
  • active 9 years ago

Best Rated Questions