← All languages
PHP function of the day
Random

Named Arguments

Pass arguments to functions by parameter name instead of position.

Description

Named arguments, introduced in PHP 8.0, allow you to pass arguments to a function by specifying the parameter name, rather than relying on the positional order. This makes code more readable, especially for functions with many optional parameters.

Named arguments can be combined with positional arguments, but named arguments must come after all positional arguments. They allow you to skip optional parameters without passing null or default values.

Named arguments work with all functions, methods, and built-in PHP functions. They are also useful in combination with PHP attributes and constructor promotion.

Example

// Without named arguments
array_slice($arr, 0, null, true);

// With named arguments — much clearer
array_slice($arr, 0, preserve_keys: true);

// Skipping optional parameters
htmlspecialchars($str, double_encode: false);

// Order doesn't matter for named args
setcookie(name: 'theme', value: 'dark', httponly: true);

Reference