The following editor will bring you an article on php FunctionUsing a variable number of parameters. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
php supports a variable number of parameter lists in usercustom functions.
In php5.5 and earlier versions, use the func_num_args(), func_get_arg(), func_get_args() function implementation.
<?php function myfunc(){ // 获取参数数量 echo func_num_args().PHP_EOL; // 获取第一个参数的值: print_r(func_get_arg(0)); echo PHP_EOL; // 获取所有参数的值 print_r(func_get_args()); echo PHP_EOL; } myfunc('a'); myfunc(1, 2, 3); myfunc(array('d','e'), array('f')); ?>
Output:
1 a Array ( [0] => a ) 3 1 Array ( [0] => 1 [1] => 2 [2] => 3 ) 2 Array ( [0] => d [1] => e ) Array ( [0] => Array ( [0] => d [1] => e ) [1] => Array ( [0] => f ) )
In php5.6 and above, you can use... syntax.
Example 1: Use...$args to replace any number of parameters
<?php function myfunc(...$args){ // 获取参数数量 echo count($args).PHP_EOL; // 获取第一个参数的值: print_r($args[0]); echo PHP_EOL; // 获取所有参数的值 print_r($args); echo PHP_EOL; } myfunc('a'); myfunc(1, 2, 3); myfunc(array('d','e'), array('f')); ?>
The output results are the same as php5.5 using func_num_args(), func_get_arg(), func_get_args( ) function is consistent.
Example 2: ArrayConvert to parameter list
<?php function add($a, $b){ echo $a + $b; } $args = array(1, 2); add(...$args); // 输出3 ?>
Example 3: Some parameters are specified, and the number of other parameters is variable
<?php function display($name, $tag, ...$args){ echo 'name:'.$name.PHP_EOL; echo 'tag:'.$tag.PHP_EOL; echo 'args:'.PHP_EOL; print_r($args); echo PHP_EOL; } display('fdipzone', 'programmer'); display('terry', 'designer', 1, 2); display('aoao', 'tester', array('a','b'), array('c'), array('d')); ?>
Output:
name:fdipzone tag:programmer args: Array ( ) name:terry tag:designer args: Array ( [0] => 1 [1] => 2 ) name:aoao tag:tester args: Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c ) [2] => Array ( [0] => d ) )
The above method of using a variable number of parameters in the PHP function is all the content shared by the editor. I hope it can give you a reference, and I hope you will learn more. Support Script Home.
The above is the detailed content of Detailed explanation of method examples using variable number of parameters in PHP. For more information, please follow other related articles on the PHP Chinese website!