Home >Backend Development >PHP Tutorial >PHP function with any number of parameters

PHP function with any number of parameters

WBOY
WBOYOriginal
2016-07-25 08:52:041012browse
  1. // function with 2 optional arguments

  2. function foo($arg1 = '', $arg2 = '') {

  3. echo "arg1: $arg1n ";

  4. echo "arg2: $arg2n";

  5. }

  6. foo('hello','world');

  7. /* prints:
  8. arg1 : hello
  9. arg2: world
  10. */

  11. foo();

  12. /* prints:
  13. arg1:
  14. arg2:
  15. */

Copy code

How to create a function that accepts any number of arguments. You need to use the func_get_args() function:

  1. // yes, the argument list can be empty

  2. function foo() {

  3. // returns an array of all passed arguments

  4. $args = func_get_args();

  5. foreach ($args as $k => $v) {

  6. echo "arg".($k+1).": $vn";
  7. }< ;/p>
  8. }

  9. foo();

  10. /* prints nothing */

  11. foo('hello');

  12. / * prints
  13. arg1: hello
  14. */

  15. foo('hello', 'world', 'again');

  16. /* prints
  17. arg1: hello
  18. arg2: world
  19. arg3: again
  20. */

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn