Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a variable parameter list

Tags:

php

Im looking for a bit of advice, I have visited this page in the manual, however it might be the wrong page or I misinterpreted the instructions as I am still confused.

enter image description here

I have the following question about the assignment above. I would like to know:

  1. 1st and foremost what is a variable-length parameter?
  2. Creating the function is not a problem however, how do I set the number of argumnets, since according to the question (if I understand it correctly) the function should be able to take any number of arguments. I guess it comes back to my 1st question regarding variable-length paramenters again...?

Thank you for reading

like image 408
Timothy Coetzee Avatar asked Apr 19 '16 06:04

Timothy Coetzee


2 Answers

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

Here is for 5.6+

<?php

function my_func(...$parameters)
{
    echo "There were ".count($parameters)." parameters passed:\n";

    foreach ($parameters as $a_parameter)
    {
        echo "Number ".$a_parameter."\n";
    }
}

echo my_func(1, 2, 3, 4, 5);

?>

https://3v4l.org/QuJqD

In (even more) simple words:

The magic happens with the ... token. my_func expects a variable number of parameters, which will be stored in the $parameters array. All that because of the ... that precedes the $parameters. Then by using count on that $parameter array we get the number of the parameters stored in that array.

As Steven in the comments nicely put it: my_func(...$parameters) has a variable length parameter list as opposed to a fixed-length parameter list which would look like function my_func($param1, $param2, $param3, $param4, $param5) which would always expect 5 parameters.

like image 137
Sharky Avatar answered Sep 19 '22 10:09

Sharky


To use variable length parameters on PHP you need the function func_get_args() instead to define the parameters on function declaration. Your function look like this:

function foo()
{
    $params_count = func_num_args();
    $params_values = func_get_args();
}

On $params_values there are all parameters which were given to the foo() function. On params_count there is the number of parameters given to foo(). You can get the number of parameters given to the foo function with func_num_args()

An example of using this functions (https://3v4l.org/TWd3v):

function foo() {
    $params_count = func_num_args();
    var_dump($params_count);
    $params_values = func_get_args();
    var_dump($params_values);
}
like image 39
Sebastian Brosch Avatar answered Sep 18 '22 10:09

Sebastian Brosch