Named Arguments

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 68 of 256

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 Tutorial Index 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 Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

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

Signed-in readers only.