This is my code:
function get_random(){
$filter_word = '1,2,3,4,5,6,7,8,9';
$array = explode(',', $filter_word);
$randomKeys = array_rand($array, 2);
$str = '';
foreach($randomKeys as $key){
$str = $array[$key];
}
return $str;
}
The problem that if I used array_rand
i must know the number of elements to can add the number in array_rand
and I can't know something like this (it's a data stored into the database) so if the elements are less than two it gives me an error:
Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array
Is there a better way to make this?
you can use count()
before using array_rand
-
function get_random(){
$filter_word = '1,2,3,4,5,6,7,8,9';
$array = explode(',', $filter_word);
$str = '';
if(count($array)>1){
$randomKeys = array_rand($array, 2);
foreach($randomKeys as $key){
$str = $array[$key];
}
}
else{
$str = $filter_word;
}
return $str;
}
I suppose you are looking for something like this:
$randCount = rand(1, count($array));
$randomKeys = array_rand($array, $randCount);