php splat operator – The Splat Operator In PHP

php splat operator – The splat operator is used as three dots before variable (…). PHP 5.6 and the Splat Operator and It’s Variadic Functions. str is called a splat operator in PHP

php splat operator

The splat operator can be used to unpack parameters to functions or to combine variables into an array.

you can use splat operator (…) to create simpler variadic functions (functions that take an undefined number of arguments).

This includes names like:

  • Ellipsis
  • Spread operator
  • Splat operator
  • Unpacking operator
  • Packing operator
  • Three dots operator
Also Read This πŸ‘‰   php import csv to mysql - Import CSV File Data into MySQL Database using PHP

PHP – Splat Operator … Variadic functions have been around since before 5.6

The Splat Operator In PHP

PHP – Splat Operator
Three dots operator

function adder(...$numbers)
{
$sum = 0;

foreach ($numbers as $number)
{
$sum += $number;
}

return $sum;
}

// Both of these work.
adder(1,2);
adder(1,2,3,4,5,6,7);

Free Live Chat for Any Issue

Don’t Miss : PHP ternary operator shorthand

Only the last parameter can use the splat operator,

...

function adder(ProductType1 ...$adds, ProductType2 ...$subs)
{
$total = 0;

foreach ($adds as $add)
{
$total += $add->getAccount();;
}

foreach ($subs as $sub)
{
$total -= $sub->getAccount();
}

return $total;
}

Argument Unpacking

function adder($arg1, $arg2)
{
return $arg1 + $arg2;
}

$args = array(1,2);
print adder(...$args); // results 3

Array of Objects Validation

class AccountPackage
{
private $m_accounts;

public function __construct(array $accounts)
{
$this->m_accounts = (function (Account ...$accounts) {
return $accounts;
})(...$accounts);
}
}

Don’t Miss : Shorthand comparisons in PHP

Also Read This πŸ‘‰   mysql check if database exists - 2 ways to check if mysql database exists

php splat

php splat operator

foo(...$args);

I hope you get an idea about php splat operator.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.