Default Argument Values

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

What Is a Default Argument Value? In simple terms: A default value is the value a parameter uses when the caller does not pass an argument for it. It makes that parameter optional . Technically: In a

What Is a Default Argument Value?

In simple terms: A default value is the value a parameter uses when the caller does not pass an argument for it. It makes that parameter optional.

Technically: In a function declaration, a parameter can be followed by = and a constant expression. If the corresponding argument is omitted in a call, PHP assigns the default expression's value to the parameter.

Why Defaults Are Useful

Many functions have settings that are the same in most calls: a currency symbol, a number of decimal places, a page size, a sort order. Defaults let common calls stay short while still allowing special cases:

formatAmount(1499);              // uses the usual settings
formatAmount(1499, 0, '$');      // overrides them when needed

Syntax

function functionName(Type $required, Type $optional = defaultValue)
{
    // ...
}

Example

<?php
function greet(string $name, string $greeting = 'Hello'): string
{
    return "$greeting, $name!";
}

echo greet('Asha') . "\n";
echo greet('Asha', 'Vanakkam') . "\n";

Output

Hello, Asha!
Vanakkam, Asha!

How It Works

  • $name has no default, so it is required.
  • $greeting has the default 'Hello', so it is optional.
  • When the second argument is omitted, $greeting is 'Hello'; when it is passed, the passed value is used.

Several Optional Parameters

<?php
function formatAmount(
    float $amount,
    int $decimals = 2,
    string $symbol = '₹',
    bool $showSymbol = true,
): string {
    return ($showSymbol ? $symbol : '') . number_format($amount, $decimals);
}

echo formatAmount(1234.5) . "\n";
echo formatAmount(1234.5, 0) . "\n";
echo formatAmount(1234.5, 2, '$') . "\n";
echo formatAmount(1234.5, showSymbol: false) . "\n";

Output

₹1,234.50
₹1,235
$1,234.50
1,234.50

Skipping Optional Parameters

With positional arguments, you cannot skip a parameter in the middle. To change only $symbol, you must also pass $decimals, even though you want its default — as in the third call.

Named arguments (PHP 8.0+) solve this: the fourth call sets only showSymbol and leaves $decimals and $symbol at their defaults. See Named Arguments.

Ordering Optional Parameters

Because positional callers must pass every earlier argument to reach a later one, order optional parameters from most frequently changed to least frequently changed.


What Can Be a Default Value?

A default value must be a constant expression — a value PHP can determine without running your code.

AllowedExample
Literals= 10, = 'INR', = true, = 2.5
null= null
Arrays= [], = ['asc', 'desc']
Constants and class constants= PHP_EOL, = self::DEFAULT_LIMIT
Constant expressions= 60 * 60, = 'v' . 2
Enum cases (PHP 8.1+)= Status::Active
new expressions (PHP 8.1+)= new NullLogger()
Not AllowedExample
Function calls= time(), = date('Y')
Variables= $defaultLimit

Example of an Invalid Default

<?php
function logEvent(string $event, int $timestamp = time())
{
    // ...
}

Result

PHP Fatal error:  Constant expression contains invalid operations

The Workaround: null as "Not Provided"

<?php
function logEvent(string $event, ?int $timestamp = null): string
{
    $timestamp ??= time();

    return date('Y-m-d H:i', $timestamp) . " $event";
}

echo logEvent('Order created', 1791545400) . "\n";

Output (the timestamp shown is in UTC)

2026-10-09 11:30 Order created
  • null is used as a marker meaning "the caller did not provide a value".
  • $timestamp ??= time(); calculates the real default inside the function — at runtime, on each call.
  • Callers can still pass their own timestamp, as in the example. (date() uses the configured timezone; the output assumes UTC.)

Defaults Are Evaluated on Every Call

In PHP, each call receives a fresh default value. Modifying a default array or object inside the function does not affect later calls:

<?php
function addTag(string $tag, array $tags = []): array
{
    $tags[] = $tag;
    return $tags;
}

print_r(addTag('php'));
print_r(addTag('mysql'));

Output

Array
(
    [0] => php
)
Array
(
    [0] => mysql
)

Each call starts with a new empty array. (Developers coming from Python, where mutable defaults are shared between calls, sometimes worry about this — PHP does not have that problem.)


Nullable Parameters With null Defaults

When null is a valid input, declare the parameter type as nullable with ? (or |null):

<?php
function searchProducts(string $query, ?string $category = null): string
{
    if ($category === null) {
        return "Searching '$query' in all categories";
    }

    return "Searching '$query' in $category";
}

echo searchProducts('lamp') . "\n";
echo searchProducts('lamp', 'Furniture') . "\n";

Output

Searching 'lamp' in all categories
Searching 'lamp' in Furniture

Version note: Older code often wrote string $category = null (without ?). That implicitly made the type nullable. Since PHP 8.4, this is deprecated ("Implicitly marking parameter $category as nullable is deprecated, the explicit nullable type must be used instead"). Always write ?string $category = null.


Optional Parameters Must Come Last

Required parameters should come before optional ones:

<?php
function makePayment(string $currency = 'INR', float $amount)
{
    // ...
}

Result (PHP 8.1 and newer)

PHP Deprecated:  Optional parameter $currency declared before required parameter $amount is implicitly treated as a required parameter

Because $amount is required, a caller must pass something for $currency anyway to reach $amount positionally — so the default can never be used. PHP treats $currency as required and warns about the misleading declaration.

Fix: Put required parameters first: function makePayment(float $amount, string $currency = 'INR').


Choosing Good Defaults

  • The most common case: the default should be what most callers want, so typical calls stay short.
  • Safe behavior: prefer defaults that are safe if forgotten — for example, bool $sendEmail = false for an action with external effects, or HTML escaping enabled by default.
  • No surprises: avoid defaults that depend on hidden state; when a value must be computed at runtime, use the null-and-??= pattern so the behavior is visible in the function body.
  • Few optional booleans: several optional bool parameters lead to calls like f($x, true, false, true). Prefer named arguments, separate functions, or an enum.

Practical Example: Building URLs

<?php
function buildUrl(
    string $path,
    array $query = [],
    bool $absolute = false,
    string $baseUrl = 'https://gocourse.in',
): string {
    $url = ($absolute ? rtrim($baseUrl, '/') : '') . '/' . ltrim($path, '/');

    if ($query !== []) {
        $url .= '?' . http_build_query($query);
    }

    return $url;
}

echo buildUrl('/courses') . "\n";
echo buildUrl('courses', ['level' => 'beginner', 'page' => 2]) . "\n";
echo buildUrl('/courses/php', absolute: true) . "\n";

Output

/courses
/courses?level=beginner&page=2
https://gocourse.in/courses/php

Step-by-Step Explanation

  1. Only $path is required; everything else has a sensible default.
  2. ltrim($path, '/') and the added '/' guarantee exactly one leading slash, whether or not the caller included one.
  3. The query string is added only when $query is not empty, using http_build_query() to encode the values safely.
  4. With absolute: true, the base URL is prepended. Named arguments let the caller skip $query without writing [].

Common Mistakes

Using Function Calls or Variables as Defaults

Effect: Fatal error "Constant expression contains invalid operations".

Fix: Default to null and compute the value inside the function.

Optional Parameters Before Required Ones

Effect: The default can never be used; PHP emits a deprecation notice.

Fix: Put required parameters first.

Implicitly Nullable Parameters

Effect: Deprecation notices in PHP 8.4+.

Fix: Write ?Type $param = null.

Passing null to Get the Default

Effect: For a non-nullable parameter, passing null causes a TypeError; for a nullable one, null is used instead of the default.

Fix: Omit the argument (or use named arguments to skip it) to get the default.

Too Many Optional Parameters

Effect: Callers pass long lists of placeholder values to reach the one they want to change.

Fix: Use named arguments, split the function, or group options into an object.


Best Practices

  • Give optional parameters defaults that match the most common use.
  • Place required parameters first, then optional ones ordered by how often they change.
  • Use explicit nullable types (?string $x = null) when null means "not provided".
  • Compute runtime defaults inside the function with ??=.
  • Combine defaults with named arguments so callers can skip parameters clearly.

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

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 Default Argument Values and get answers drawn from it.

Signed-in readers only.