简体   繁体   中英

Passing an array through a PHP function

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 ie:

$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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM