There is this function :
mt_rand(1,5)
=> randomly selects between 1 and 5.
and another method:
$items = array(1, 4, 5, 7, 8);
echo $items[array_rand($items)];
My question is about second method. I want to use it in this way. echo array_rand(1,4,5,7,8);
Is there a way to do this, or how can I do it? I would like to use the function without defining the array first. Everything in one place. thanks!
Note: I want to use it for unordered list.
You can flip the array, then use array_rand()
, this will inverse the key-value pairs (so the key becomes the value, and vice-versa). This will mean that when you use array_rand()
, you get the new key - which was originally the value.
echo array_rand(array_flip($items));
If you want to define a function with a variable number of parameters, you can do that too, by using func_get_args()
.
function random_value() {
// If there were no values returned, return false.
if (func_num_args() == 0) {
return false;
}
// Get all the values supplied
$values = func_get_args();
$random = array_rand($values);
return $values[$random];
}
Though you can just define the array inline, by doing
echo array_rand(array_flip([1, 3, 7, 8]));
Use helper function
You can add helper function:
function arr_rand($array){
return $array[array_rand($array)];
}