How to get random value out of an array?


Question

I have an array called $ran = 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?

1
110
7/17/2019 12:17:23 PM

Accepted Answer

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.

211
10/29/2009 12:44:44 PM

PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php

$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon