Search code examples
phpsyntaxoperators

What is the meaning of three dots (...) in PHP?


While I am installing Magento 2 on my Server, I got an error. After investigating the code and found that there are three dots (...), which is producing the error. I included the code I found below:

return new $type(...array_values($args));

What is this operator called, and what is its purpose?


Solution

  • This is literally called the ... operator in PHP, but is known as the splat operator from other languages. From a 2014 LornaJane blog post on the feature:

    This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like. It's easiest to see with an example:

    function concatenate($transform, ...$strings) {
        $string = '';
        foreach($strings as $piece) {
           $string .= $piece;
        }
        return($transform($string));  
     }
    
    echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
    

    (This would print I'D LIKE 6 APPLES)

    The parameters list in the function declaration has the ... operator in it, and it basically means " ... and everything else should go into $strings". You can pass 2 or more arguments into this function and the second and subsequent ones will be added to the $strings array, ready to be used.