Create Variable List

I need some advice, I visited this page in the manual, however it may not be the right page or I misinterpreted the instructions as I am still confused.

enter image description here

I have the following question about the appointment above. I'd like to know:

  • First of all, what is a variable length parameter?
  • However, creating a function is not a problem, how to set the number of arguments, because according to the question (if I understand correctly) the function should be able to accept any number of arguments. I guess this goes back to my 1st question about variable length parammers ...?

Thanks for reading

+4
source share
6 answers

PHP, func_get_args() . :

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

$params_values , foo(). params_count , foo(). , foo, func_num_args()

(https://3v4l.org/TWd3v):

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

PHP . ... PHP 5.6 , func_num_args(), func_get_arg() func_get_args() PHP 5.5 .

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

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

( ) :

.... my_func variable, $parameters. - ..., $parameters. , count $parameter, , .

: my_func(...$parameters) , , function my_func($param1, $param2, $param3, $param4, $param5), 5.

+3
<?php
    function my_func(){
        $args = func_num_args();
        $args_list = func_get_args();
        echo 'There were '.$args.' numbers passed:<br>';
        foreach($args_list as $k=>$v){
            echo 'Number '.$v.'.<br>';
        }
    }

    my_func(1,2,3,4,5);
    my_func(3,4,5);
?>

1:

There were 5 numbers passed:
Number 1.
Number 2.
Number 3.
Number 4.
Number 5.

2:

There were 3 numbers passed:
Number 3.
Number 4.
Number 5.
+1

PHP , , PHP func_get_args()

function noprms(){
    $count = func_num_args();
    $args = func_get_args();
    echo "There were $count arguments passed \n";
    echo "Number ".implode(",\nNumber ",$args)."\n";
}

noprms(1,2,3,4,5)."\n";
noprms(1,2,3,4,5,6,7,8,9)."\n";

Demo

+1

, : :

In PHP 5.6 and later, argument lists may include ... a token to indicate that a function accepts a variable number of arguments.

Variable arguments are available as an array (so you can encode them).

Copy the paste from the manual:

<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
    $acc += $n;
}
return $acc;
}

echo sum(1, 2, 3, 4);
0
source

All Articles