Friday 26 June 2015

Splat Operator in PHP

The splat operator was introduced in PHP starting with version 5.6, so, to can use it and test the examples from this page, you need PHP 5.6+.
The Splat Operator is represented by three dots (...), and can be used to define functions that can be called with a variable number of arguments.
1. This operator can be used when the function is called, before an array argument.
<?php
function add($a, $b, $c) {
  return $a + $b + $c;
}

$arguments = [8, 9];     // array with values for $b and $c parameters
echo add(5, ...$arguments);      // 22
?>
2. The splat operator can also be used when the function is defined, before a parameter that represents an array of arguments.
<?php
// $params is an array containing the remaining arguments
function add($opt = 0, ...$params) {
  $sum = $opt + array_sum($params);
  echo '$opt is '. $opt .' / $params contains '. count($params .' arguments / $sum = '. $sum;    
}

add();             // $opt is 0 / $params contains 0 arguments / $sum = 0
add(1);            // $opt is 1 / $params contains 0 arguments / $sum = 1
add(5, 6);         // $opt is 5 / $params contains 1 arguments / $sum = 11
add(5, 6, 7);      // $opt is 5 / $params contains 2 arguments / $sum = 18
add(5, 6, 7, 8);   // $opt is 5 / $params contains 3 arguments / $sum = 26
?>

0 comments:

Post a Comment