Reputation: 36786
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?
Upvotes: 2
Views: 140
Reputation: 187
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);
}
Upvotes: 0
Reputation: 25781
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 :)
Upvotes: 8
Reputation: 39704
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"
}*/
Upvotes: 0