Variable Argument Function In PHP
PHP supports variable-length argument function. It means you can pass 0, 1 or n number of arguments in the function. To do so, you need to use 3 ellipses (dots) before the argument name.
A simple example of a PHP variable-length argument function.
Example
<?php
function addCal(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
echo add(1,2,3,4);
?>
Output:10
1. func_num_args()
- This function returns the number of the argument passed into the current user-defined function. The return type is an integer.
- Func_num_args() will generate a warning if called from outside of a user-defined function.
Syntax
int func_num_args(void)
Example
<?php
function callMe()
{
$value = func_num_args();
echo "Number of arguments : ".$value;
}
callMe(1,2,3,4);
?>
Output :
Number of arguments : 4
2. func_get_arg()
- Returns an item from the argument list.
Syntax
mixed func_get_arg(int arg_num)
- Returns the argument which is at the arg_num’th offset into a user-defined function’s argument list.
- The function argument is counted starting from zero.
- func_get_arg() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter instead, its result may be assigned to a variable, which can then be passed to the function.
Example
<?php
function callMe()
{
$num_arg = func_num_args();
echo "Number of arguments : ".$num_arg."<br/>";
if($num_arg >= 2)
{
echo "Seccond arguments is : ".func_get_arg(1);
}
}
callMe(1,2,3,4);
?>
Output :
Number of arguments : 4
Seccond arguments is : 2
3. func_get_args()
- Returns the array of arguments passed into the current user-defined function.
Syntax
array func_get_args(void)
Example
<?php
function callMe()
{
$num_args = func_num_args();
if($num_args > 0)
{
$num = func_get_args();
foreach($num as $value)
{
echo $value."<br/>";
}
}
}
callMe("Hello","World");
?>
Output :
Hello
World
Series:
PHP Tutorials Hub
