Every so often I find myself needing to pass an unknown amount of arguments into a function. For example, assume you want to create a function to add a bunch of variables: add( $a, $b, $c, $d, … ) This can easily be done using the PHP function func_get_args().
1 2 3 4 5 6 7 8 9 10 11 | function add() { $total = 0; $args = func_get_args(); foreach ($args as $key => $val) { $total += $val; } return $total; } |
You can then call the function with as many arguments as you want.
1 | echo add( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ); |
Post a comment
Hello guest, care to post a comment?