通过PHP函数传递数组
Im sure there has to be a way to do this:
I want it so that If I call a function like this...
callFunction("var1","var2","var3");
the function 'callFunction' will turn these variables into an array i.e:
$array[0] = "var1";
$array[1] = "var2";
$array[2] = "var3";
I want it to generate this array no matter how many variables are listed when calling the function, is this possible?
我确定必须有办法做到这一点: p>
I 想要这样,如果我调用这样的函数... p>
callFunction(“var1”,“var2”,“var3”);
code>
函数'callFunction'将这些变量转换为数组,即: p>
$ array [0] =“var1”;
$ array [1] =“var2”;
$ array [2] =“var3”;
code> pre>
我希望它生成这个数组,无论多少 调用函数时会列出变量,这可能吗? p>
div>
You can simply do the following:
function callFunction() {
$arr = func_get_args();
// Do something with all the arguments
// e.g. $arr[0], ...
}
func_get_args
will return all the parameters passed to a function. You don't even need to specify them in the function header.
func_num_args
will yield the number of arguments passed to the function. I'm not entirely sure why such a thing exists, given that you can simple count(func_get_args())
, but I suppose it exist because it does in C (where it is actually necessary).
If you ever again look for this kind of feature in a different language, it is usually referred to as Variadic Function, or "varargs" if you need to Google it quickly :)
Just return func_get_args()
from that function:
function callFunction(){
return func_get_args();
}
$array = callFunction("var1","var2","var3","var4","var5");
var_dump($array);
/*array(5) {
[0]=>
string(4) "var1"
[1]=>
string(4) "var2"
[2]=>
string(4) "var3"
[3]=>
string(4) "var4"
[4]=>
string(4) "var5"
}*/
Call your function like this.
callFunction( array("var1", "var2", "var3", "var4", "var5") );
and create your function like this.
function callFunction($array)
{
//here you can acces your array. no matter how many variables are listed when calling the function.
print_r($array);
}