bagwaa
bagwaa

Reputation: 359

PHP Functions - Maximum number of arguments

In PHP, when defining a function what is the maximum number of arguments that you can create? This isn't something I am doing, just a question that popped up when discussing it with a colleague :)

Would this be purely down a memory limitation? effectively unlimited?

Upvotes: 18

Views: 12316

Answers (4)

KodeFor.Me
KodeFor.Me

Reputation: 13511

I don't really know what are the limits, but either way, if you create a function with too many arguments your code will not be so easy to read it. In case you like to add many function arguments you can do something like that:

$option = array(
    'arg_1' => 'value',
    'arg_2' => 'value',
    ....
    'arg_x' => 'value'
);

function function_name($args = "")
{
    $defaults = array(
        'arg_1' => 'default_value',
        'arg_2' => 'default_value'
        ....
        'arg_x' => 'default_value'
    );

    $arguments = array_merge($defaults, (array)$args);
    extract($arguments);

    echo $arg_1;
    echo $arg_x;
}

Upvotes: 3

hakre
hakre

Reputation: 197775

when defining a function what is the maximum number of arguments that you can create?

I'm not aware of specific limit in the number of arguments as a fixed number. A quick test revealed that I had no problems to define a function with 255 555 arguments. It does take some time to define the function and to execute it. However, it works.

As the number was raised, I was running into a memory limit which could be string limit. You might want to improve the test-case, use a buffer and save the file to disk sequentially and include it then:

$count = 255555;

$code = 'function test(%s) {return 1;}; return test();';

$params = ltrim(implode('=0, $p', range(0, $count)), '0, =').'=0';

echo eval(sprintf($code, $params));

Upvotes: 7

CodeCaster
CodeCaster

Reputation: 151594

Arguments to a function are pushed on a stack, after which the function is called which in turn reads the stack and uses those values as parameters.

So as long as the stack isn't full, you can keep adding parameters, but it'll depend on the situation, and at design-time you won't know the stack size.

But I really hope this is pure a technical discussion and you don't need it IRL. ;-)

Upvotes: 9

samura
samura

Reputation: 4395

There is no limit. And you can always use func_get_args(), func_get_arg() and func_num_args() to avoid writing all the arguments in the function definition.

Upvotes: 16

Related Questions