2

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?

6
  • 8
    func_get_args()? Commented Oct 1, 2012 at 9:24
  • Is the question now, whether and how to pass an array to a function, or whether a function can be called with variable number of arguments? Commented Oct 1, 2012 at 9:24
  • 1
    Why don't you want to use array ??? Commented Oct 1, 2012 at 9:25
  • 1
    @Havelock - I interpret it as "how to declare a varaidic function which will put all of its arguments into an array". If that is the case, don't roll your own, use array(). If you want to do more, do as @DCoder says and use func_get_args(). Commented Oct 1, 2012 at 9:26
  • This page in the manual might be insightful for you, too: Variable-length argument lists Commented Oct 1, 2012 at 9:44

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

@George you would need to add return $arg;
0

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"
}*/

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.