I have a (simplified) function that uses开发者_开发知识库 in_array()
to check if a value is in an array:
function is($input) {
$class = array('msie','ie','ie9');
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
if (is('msie'))
echo 'Friends don\'t let friends use IE.';
I want to break this into two separate functions, where the first defines the array:
function myarray() {
$class = array('msie','ie','ie9');
}
and the second runs the check—either like this:
function is($input) {
myarray();
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
Or this:
function is($input) {
global $class;
$is = FALSE;
if (in_array($input, $class)) {$is = TRUE;}
return $is;
}
But both of the above cause this error:
Warning: in_array() [function.in-array]: Wrong datatype for second argument in /home/vanetten/temp.ryanve.com/PHP/airve.php on line 73
What is the proper way use an array from one function in another? Can an array be a global variable? How do I make this work? Is it more efficient to use a global variable or to call the first function within the second function. Any help is definitely appreciated.
Return the array from the first function:
function myarray() {
return array('msie','ie','ie9');
}
function is($input) {
$array = myarray();
return in_array($input, $array);
// or even just
// return in_array($input, myarray());
}
function is($input) {
$class = myarray();
$is = false;
...
Easiest way (which also negates the use of global variables, which is a bad practice since using $class
somewhere else down the line may result in unexpected behavior) is something like
function myarray() {
return array('msie','ie','ie9');
}
function is($input) {
$array = myarray();
$is = FALSE;
if (in_array($input, $array)) {$is = TRUE;}
return $is;
}
if (is('msie'))
echo 'Friends don\'t let friends use IE.';
In this example, we just make myarray()
return the needed array. In is()
, add the line $array = myarray()
, which will save the array from myarray()
, so it is useable from is()
as the alias $array
. Then simply change $class
to $array
, and it should work fine.
精彩评论