Functions with Arbitrary Number of Arguments


SUBMITTED BY: PYOGI111

DATE: Oct. 30, 2015, 5:58 a.m.

FORMAT: Text only

SIZE: 943 Bytes

HITS: 576

  1. You may already know that PHP allows you to
  2. define functions with optional arguments. But there
  3. is also a method for allowing completely arbitrary
  4. number of function arguments. First, here is an example with just optional
  5. arguments: // function with 2 optional arguments
  6. function foo($arg1 = '', $arg2 = '') { echo "arg1: $arg1\n";
  7. echo "arg2: $arg2\n"; } foo('hello','world');
  8. /* prints:
  9. arg1: hello
  10. arg2: world
  11. */ foo();
  12. /* prints:
  13. arg1:
  14. arg2:
  15. */ Now, let's see how we can build a function that
  16. accepts any number of arguments. This time we are
  17. going to utilize func_get_args(): // yes, the argument list can be empty
  18. function foo() { // returns an array of all passed arguments $args = func_get_args(); foreach ($args as $k => $v) { echo "arg".($k+1).": $v\n"; } } foo();
  19. /* prints nothing */ foo('hello');
  20. /* prints
  21. arg1: hello
  22. */ foo('hello', 'world', 'again');
  23. /* prints
  24. arg1: hello
  25. arg2: world
  26. arg3: again
  27. */

comments powered by Disqus