Current Location: Home> Latest Articles> PHP Function Parameters Explained: Using Variadic Parameters and Callables

PHP Function Parameters Explained: Using Variadic Parameters and Callables

M66 2025-09-17

Special Parameters in PHP Functions

In PHP development, function parameters are very flexible. Two special parameters are particularly common: the variadic parameter ...$var and the callback parameter callable. They are used to handle an indefinite number of arguments and to pass executable callback logic into functions.

Variadic Parameter ...$var

A variadic parameter allows a function to accept any number of arguments, which are automatically stored as an array. This is especially convenient when performing aggregation tasks such as summing values.

<?php
function sum(...$numbers) {
  $total = 0;
  foreach ($numbers as $number) {
    $total += $number;
  }
  return $total;
}

echo sum(1, 2, 3, 4, 5); // Output: 15
?>

In this example, the sum function uses the variadic parameter ...$numbers to accept multiple numbers and calculate their total.

Callable Functions

The callable parameter type allows a function to receive another function as an argument, and execute it when needed. This is often used for filtering, sorting, or applying custom logic.

<?php
function filterArray(array $array, callable $callback) {
  $filteredArray = [];
  foreach ($array as $element) {
    if ($callback($element)) {
      $filteredArray[] = $element;
    }
  }
  return $filteredArray;
}

$callback = function ($value) {
  return $value > 10;
};

$filteredArray = filterArray([1, 2, 10, 15, 20], $callback);
print_r($filteredArray); // Output: [15, 20]
?>

Here, the filterArray function takes an array and a callback function. The callback is used to check whether each element meets a condition, enabling flexible filtering logic.

Key Notes

  • The variadic parameter must be the last in the function’s parameter list.
  • A callable parameter can be an anonymous function or the name of an existing function.

By leveraging these two parameter types, PHP functions become more extensible and flexible, giving developers greater power and reusability in their code.