Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a PHP function accept an unlimited number of parameters? [duplicate]

Tags:

In PHP there are functions like unset() that support any number of parameter we throw at them.

I want to create a similar function that is capable of accepting any number of parameters and process them all.

Any idea, how to do this?

like image 373
Starx Avatar asked Jun 20 '10 06:06

Starx


People also ask

How many parameters can a function have PHP?

PHP native functions According to the manual, PHP functions may accept up to 12 arguments. This is the case for two functions : imapepstext and snmp3_set.

What is the maximum number of parameters a function can have?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.

Can echo in PHP accept more than 1 parameter?

Definition and Usage. The echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error.

What can take multiple parameters in PHP?

Introduction to the PHP function parameters When a function has multiple parameters, you need to separate them using a comma ( , ). The concat() function has two parameters $str1 and $str2 . In this example, the $str1 will take the first argument 'Welcome ' , and the $str2 will take the second argument 'Admin' .


1 Answers

In PHP, use the function func_get_args to get all passed arguments.

<?php function myfunc(){     $args = func_get_args();     foreach ($args as $arg)       echo $arg."/n"; }  myfunc('hello', 'world', '.'); ?> 

An alternative is to pass an array of variables to your function, so you don't have to work with things like $arg[2]; and instead can use $args['myvar']; or rewmember what order things are passed in. It is also infinitely expandable which means you can add new variables later without having to change what you've already coded.

<?php function myfunc($args){     while(list($var, $value)=each($args))       echo $var.' '.$value."/n"; }  myfunc(array('first'=>'hello', 'second'=>'world', '.')); ?> 
like image 87
Aaron Harun Avatar answered Sep 21 '22 14:09

Aaron Harun