PHP Splat Operator Code Example

Hello devs

In this example, I am going to explain PHP splat operator example with source code. So from this tutorial, you’ll learn about the php splat operator that accept unlimited variable number of arguments.

So let me introduce the php splat operator in a brief with an example. Look, the following function defines a method called sum() that returns the sum of two integers:

function sum(int $x, int $y)
{
    return $x + $y;
}

echo sum(10, 20); // 30

 

Now we want to pass unlimited parameters to this function. How we can do that? We can do that using php splat operator. You will also learn php splat operator type hint example from this example.

So now In this example, we place the ... operator in front of the $numbers argument. The sum() function now accepts unlimited variable of number arguments.

function sum(...$numbers)
{
    $total = 0;
    for ($i = 0; $i < count($numbers); $i++) {
        $total += $numbers[$i];
    }

    return $total;
}
echo sum(10, 20) . '
'; // 30 echo sum(10, 20, 30) . '
'; // 60

 

We can make it more efficient using type hints, like: 

function sum(int ...$numbers): int
{
    $total = 0;
    for ($i = 0; $i < count($numbers); $i++) {
        $total += $numbers[$i];
    }

    return $total;
}

 

Read also: PHP Variadic Functions Code Example

 

Hope it can help you.

 

#php