Named Arguments

Yo Yogesh.M Updated 17 Oct 2026
6 min read ·Lesson 46 of 102
In this post

What Are Named Arguments? In simple terms: Named arguments let you pass values to a function by writing the parameter name next to each value, instead of relying only on the order of the values. Techn

What Are Named Arguments?

In simple terms: Named arguments let you pass values to a function by writing the parameter name next to each value, instead of relying only on the order of the values.

Technically: Introduced in PHP 8.0, named arguments use the syntax parameterName: value in a function call. PHP matches each named argument to the parameter with that name, so the order of named arguments does not matter, and optional parameters in between can be skipped.

// Positional: what do 0 and false mean?
formatAmount(1234.5, 0, '₹', false);

// Named: self-explanatory
formatAmount(1234.5, decimals: 0, showSymbol: false);

Why Named Arguments Were Added

  1. Readability: calls such as f(true, false, null, 3) give no hint about what each value means.
  2. Skipping optional parameters: without named arguments, changing the last optional parameter required repeating the defaults of every parameter before it.
  3. Order independence: you cannot accidentally swap two values of the same type.

Syntax

functionName(parameterName: value, otherParameter: value);
  • The name is written without the $.
  • A colon separates the name and the value.
  • Named arguments can be combined with positional arguments, but positional ones must come first.

Example

<?php
function createUser(
    string $name,
    string $role = 'viewer',
    bool $active = true,
    ?string $team = null,
): string {
    return sprintf(
        '%s | role: %s | active: %s | team: %s',
        $name,
        $role,
        $active ? 'yes' : 'no',
        $team ?? 'none',
    );
}

echo createUser('Asha', team: 'Sales') . "\n";
echo createUser(name: 'Bala', active: false) . "\n";
echo createUser(team: 'Support', name: 'Charu', role: 'editor') . "\n";

Output

Asha | role: viewer | active: yes | team: Sales
Bala | role: viewer | active: no | team: none
Charu | role: editor | active: yes | team: Support

How Each Call Works

  1. createUser('Asha', team: 'Sales') — 'Asha' is positional (first parameter). team is set by name. role and active keep their defaults, even though they come before team in the declaration.
  2. createUser(name: 'Bala', active: false) — all arguments are named; role and team use defaults.
  3. createUser(team: 'Support', name: 'Charu', role: 'editor') — named arguments in any order.

Without named arguments, the first call would have to be written as createUser('Asha', 'viewer', true, 'Sales'), repeating two defaults just to reach $team.


Named Arguments With Built-in Functions

Named arguments work with built-in functions too, using the parameter names shown in the PHP manual.

<?php
echo str_pad('7', 3, '0', STR_PAD_LEFT) . "\n";
echo str_pad(string: '7', length: 3, pad_string: '0', pad_type: STR_PAD_LEFT) . "\n";

echo htmlspecialchars('& <b>', double_encode: false) . "\n";

echo json_encode(['city' => 'சென்னை'], flags: JSON_UNESCAPED_UNICODE) . "\n";

var_dump(in_array(needle: '5', haystack: [5], strict: true));

echo implode(', ', array_fill(start_index: 0, count: 3, value: 'x')) . "\n";

Output

007
007
& <b>
{"city":"சென்னை"}
bool(false)
x, x, x

Why This Helps

  • htmlspecialchars(..., double_encode: false) — the double_encode parameter is the fourth parameter. Without named arguments, you would need to pass the default flags and encoding first: htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false).
  • in_array(..., strict: true) — makes it obvious that the true means strict comparison.
  • array_fill(start_index: ..., count: ..., value: ...) — prevents mixing up two integer arguments.

The names of built-in parameters are listed in each function's signature in the manual (for example, str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT)).


Rules and Errors

Positional Arguments Must Come First

createUser(name: 'Asha', 'editor');

Result: Fatal error at compile time: Cannot use positional argument after named argument. Once you start naming arguments, every following argument must also be named.

Unknown Parameter Names

<?php
function createUser(string $name, string $role = 'viewer'): string
{
    return "$name ($role)";
}

try {
    echo createUser('Asha', email: 'asha@example.com');
} catch (Error $e) {
    echo get_class($e) . ": " . $e->getMessage() . "\n";
}

Output

Error: Unknown named parameter $email

PHP checks names when the call happens. A typo in a parameter name causes an error instead of being silently ignored.

Setting the Same Parameter Twice

<?php
function createUser(string $name, string $role = 'viewer'): string
{
    return "$name ($role)";
}

try {
    echo createUser('Asha', name: 'Bala');
} catch (Error $e) {
    echo get_class($e) . ": " . $e->getMessage() . "\n";
}

Output

Error: Named parameter $name overwrites previous argument

'Asha' was already assigned positionally to $name, so naming $name again is an error.

Required Parameters Are Still Required

createUser(role: 'editor');   // ArgumentCountError: $name was not passed

Named arguments only change how values are matched; every required parameter must still receive a value.


Unpacking Arrays Into Named Arguments (PHP 8.1+)

When an array with string keys is unpacked with ..., the keys are used as parameter names:

<?php
function createUser(
    string $name,
    string $role = 'viewer',
    bool $active = true,
    ?string $team = null,
): string {
    return sprintf('%s | role: %s | active: %s | team: %s', $name, $role, $active ? 'yes' : 'no', $team ?? 'none');
}

$formData = ['name' => 'Dev', 'role' => 'admin'];

echo createUser(...$formData) . "\n";

Output

Dev | role: admin | active: yes | team: none

This is convenient when arguments are prepared as an associative array, such as configuration values. Make sure the keys come from your own code, not directly from user input: unexpected keys cause "Unknown named parameter" errors.


Collecting Extra Named Arguments With Variadics

A variadic parameter (...$name) collects extra named arguments into an array with string keys:

<?php
function htmlTag(string $tag, string $content, string ...$attributes): string
{
    $html = '';

    foreach ($attributes as $attribute => $value) {
        $html .= sprintf(' %s="%s"', $attribute, htmlspecialchars($value));
    }

    return "<$tag$html>" . htmlspecialchars($content) . "</$tag>";
}

echo htmlTag('a', 'View course', href: '/courses/php', class: 'btn') . "\n";

Output

<a href="/courses/php" class="btn">View course</a>

href and class are not declared parameters, so they are collected in $attributes as ['href' => '/courses/php', 'class' => 'btn']. Variadic functions are covered in Variadic Functions.


Parameter Names Become Part of the API

With named arguments, callers depend on your parameter names, not only on their order. Renaming a parameter — for example, from $team to $department — breaks every call that uses team:.

Practical consequences:

  • Choose clear parameter names from the start.
  • Treat renaming a parameter of a public function as a breaking change, just like removing it.
  • In libraries, document whether named arguments are supported for a function.

When to Use Named Arguments

SituationRecommendation
The function has one or two obvious parameters (strlen($s), max($a, $b))Positional
Boolean or null arguments whose meaning is unclearNamed
You want to set an optional parameter far down the listNamed
Several parameters of the same type that could be swappedNamed
Constructors with many optional settingsNamed

Common Mistakes

Positional Argument After a Named One

Effect: Fatal compile error.

Fix: Put all positional arguments first.

Typos in Parameter Names

Effect: Error: Unknown named parameter.

Fix: Check the function signature; editors autocomplete parameter names.

Using $ in the Name

createUser('Asha', $team: 'Sales');   // parse error

Fix: Write the name without $: team: 'Sales'.

Unpacking User-Controlled Arrays

Effect: Unexpected keys cause errors, and callers can set parameters you did not intend to expose.

Fix: Build the argument array from validated, known keys.

Renaming Parameters Without Considering Callers

Effect: Existing named calls break.

Fix: Treat parameter names as part of a function's public contract.


Best Practices

  • Use named arguments to clarify boolean, null, and same-typed arguments.
  • Use them to skip optional parameters instead of repeating default values.
  • Keep positional arguments first, followed by named ones.
  • Choose stable, descriptive parameter names, since callers depend on them.
  • Use positional arguments for short, obvious calls; named arguments are a readability tool, not a requirement.

Official reference: https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting
Ask about this post
AI Ask about this post

Ask questions about Named Arguments and get answers drawn from it.

Signed-in readers only.