• support@answerspoint.com

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


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?



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 7 years ago
  • Sunny Solu


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 7 years ago
  • Sandy Hook

Your Answer

    Facebook Share        
  • asked 7 years ago
  • viewed 1762 times
  • active 7 years ago

Best Rated Questions