Php write function with unknown parameters?

How can I write a function in php with an unknown number of parameters, e.g.

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

But when you call a function that you can use:

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

So more parameters can be sent, since the number of parameters will be unknown.

+6
source share
4 answers

func_get_args ()

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

Remember that although you can do this, you should not define any arguments in the function declaration if you intend to use func_get_args () - simply because it becomes very confusing if / when any of the specified arguments are omitted

Similar functions about arguments

  • func_get_arg ()
  • func_get_args ()
  • func_num_args ()
+11
source

Only for those who found this topic on Google.

In PHP 5.6 and above, you can use ... to specify an 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.

+8
source

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

 $args = func_get_args(); 

You can then use the array or iterate over it, which is best for your use case.

+2
source

You can also use an array:

 <?php function example($args = array()) { if ( isset ( $args["arg1"] ) ) echo "Arg1!"; } example(array("arg1"=>"val", "arg2"=>"val")); 
0
source

Source: https://habr.com/ru/post/895582/


All Articles