11

How would I go about writing a function in php with an unknown number of parameters, for example

function echoData (parameter1, parameter2,) {
    //do something
}

But when you call the function you can use:

echoData('hello', 'hello2', 'hello3', 'hello'4);

So that more parameters can be sent as the number of parameters will be unknown.

1

4 Answers 4

18

Just for those who found this thread on Google.

In PHP 5.6 and above you can use ... to specify the unknown number of parameters:

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4); // 10

$numbers is an array of arguments.

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

Comments

15

func_get_args()

function echoData(){
    $args = func_get_args();
}

Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted

Similar functions about arguments

  • func_get_arg()
  • func_get_args()
  • func_num_args()

2 Comments

Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted.
@Dave: Nice catch. I'll add it to my answer
2

use func_get_args() to retrieve an array of all parameters like that:

$args = func_get_args();

You can then use the array or iterate over it, whatever suits your use-case best.

Comments

0

You can also use an array:

<?php    
function example($args = array())
{
    if ( isset ( $args["arg1"] ) )
        echo "Arg1!";
}

example(array("arg1"=>"val", "arg2"=>"val"));

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.