Is there a way to define a function in PHP that lets you define a variable amount of parameters?
in the language I am more familiar with it is like so:
function myFunction(...rest){ /* rest == array of params */ return rest.length; }
myFunction("foo","bar"); // returns 2;
Thanks!
Yes. Use func_num_args()
and func_get_arg()
to get the arguments:
<?php
function dynamic_args() {
echo "Number of arguments: " . func_num_args() . "<br />";
for($i = 0 ; $i < func_num_args(); $i++) {
echo "Argument $i = " . func_get_arg($i) . "<br />";
}
}
dynamic_args("a", "b", "c", "d", "e");
?>
In PHP 5.6+ you can now use variadic functions:
<?php
function dynamic_args(...$args) {
echo "Number of arguments: " . count($args) . "<br />";
foreach ($args as $arg) {
echo $arg . "<br />";
}
}
dynamic_args("a", "b", "c", "d", "e");
?>