Variable-length argument list in PHP

Given a set of arguments whose length is unknown at present, we will see how a function can work with these unknown numbers of arguments whose quantity will vary depending on the requirement.

We will take up each word one by one to deeply understand the topic we are dealing with.

  • Variable: It is the number of arguments keep changing.
  • Length: It refers to the number of arguments.
  • Argument: It refers input passed to a function.

Now, the point of interest lies at the word list, all the arguments passed at its call will go the function as an array. The values will be retrieved like they are being from an array.

Accessing Variable Arguments Method: In this, the function is made to accept variable arguments and work accordingly. The variable which has to have multiple numbers of arguments is declared with “…”(triple dots).

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    function sum(...$numbers) {
      $res = 0;
      foreach($numbers as $n) {
          $res+=$n;
        }
      return $res;
    }
      
    echo(sum(1,2,3,4)."\n");
    echo(sum(5,6,1));
    ?>

    chevron_right

    
    

  • Output:
    10 
    12

Providing Variable Arguments Method: You can also use “…”(triple dots) when calling functions to unpack an array or Traversable variable or literal into the argument list.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    function add($a,$b) {
      return $a + $b ;
    }
    echo add(...[1, 2])."\n";
      
    $a = [1, 2];
    echo add(...$a);
    ?>

    chevron_right

    
    

  • Output:
    3
    3
    

Type hinted Variable Arguments Method: It is also possible to add a type of hint before the … token. If this is present, then all arguments captured by … must be objects of the hinted class.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    function total_intervals($unit, DateInterval ...$intervals) {
        $time = 0;
        foreach ($intervals as $interval) {
            $time += $interval->$unit;
        }
        return $time;
    }
      
    $a = new DateInterval('P1D');
    $b = new DateInterval('P2D');
    echo total_intervals('d', $a, $b).' days';
        
      
    ?>

    chevron_right

    
    

  • Output:
     3 days



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.