Reputation: 349
I tried the below code for print a random value from an array for 70 times but i am getting an error as such : ' array_rand() expects parameter 1 to be array'.
$q= array("top","below","right","left");
function ran(){
$rand_keys = array_rand($q, 1);
return $rand_keys[0];
}
for ($m=0; $m <70 ; $m++) {
ran($q);
echo ran();
}
Upvotes: 0
Views: 2098
Reputation: 1784
Yes, add $q as a parameter. Also, you should return the value of $q at index $rand_key. You kinda miss used array_rand return value.
Giving you this code :
$q = array("top","below","right","left");
for ($m = 0; $m <70 ; $m++) {
echo ran($q).' ';
}
function ran($q){
$rand_keys = array_rand($q, 1);
return $q[$rand_keys];
}
Upvotes: 1
Reputation: 781004
Global variables are not normally visible inside functions. You should put $q
in the function parameter list:
function ran($q) {
$rand_keys = array_rand($q, 1);
return $rand_keys[0];
}
Then call it as:
echo ran($q);
Upvotes: 3