How to count the number of parameters passed in a PHP function?
Use func_num_args() inside the function. It returns how many arguments were passed. func_get_args() returns them in an array.
<?php
function total() {
return func_num_args();
}
echo total(10, 20, 30);
?>
Output:
Tutorials Class - Output Window
3
In modern PHP the clearer way is a variadic parameter (...$args), and then count($args).
<?php
function total(...$args) {
return count($args);
}
echo total(10, 20, 30);
?>
Output:
Tutorials Class - Output Window
3
Learn more in PHP Functions.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Functions |
| Exercises & Assignments |
|---|
| Factorial program in PHP using recursive function |
| Write a PHP program to calculate area of rectangle |
| Interview Questions & Answers |
|---|
| What is PHP Function? |
| What is PHP floor() function? |
| How to count the number of parameters passed in a PHP function? |
| How can you pass a variable by reference in PHP? |