Skip to content

PHP Tutorial Functions

Default Parameters

Lesson 107 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Give a parameter a default value and the caller may leave it out. That makes the argument optional.

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

echo greet("Mira") . "\n";
echo greet("Mira", "Welcome");
Output
OUTPUT
Hello, Mira!
Welcome, Mira!

If the caller passes a second argument, it replaces the default.

Defaults go last

Optional parameters belong after required ones. Since PHP 8.0, a required parameter after an optional one is deprecated, because you could never skip the optional one.

index.php
PHP
<?php
function createUser(string $name, string $role = "viewer", bool $active = true): string
{
    return "$name ($role) " . ($active ? "active" : "inactive");
}

echo createUser("Ravi") . "\n";
echo createUser("Asha", "admin") . "\n";
echo createUser("Cy", "editor", false);
Output
OUTPUT
Ravi (viewer) active
Asha (admin) active
Cy (editor) inactive

What can be a default

Defaults must be values PHP knows without running code: numbers, strings, true, false, null, arrays and constants.

index.php
PHP
<?php
const DEFAULT_LIMIT = 10;

function getPosts(int $limit = DEFAULT_LIMIT, array $tags = []): string
{
    return "Limit $limit, tags: " . count($tags);
}

echo getPosts() . "\n";
echo getPosts(5, ["php"]);
Output
OUTPUT
Limit 10, tags: 0
Limit 5, tags: 1

A null default

Use null when the real default needs to be calculated inside the function.

index.php
PHP
<?php
function formatDate(?string $date = null): string
{
    $date ??= "today";
    return "Date: $date";
}

echo formatDate() . "\n";
echo formatDate("2026-01-15");
Output
OUTPUT
Date: today
Date: 2026-01-15

Write the ? yourself. Older code wrote string $date = null, which made the type nullable by accident. PHP 8.4 deprecates this “implicit nullable” style, so always write ?string $date = null.

Skipping an optional argument

If you want to give the third argument but not the second, positional calls force you to repeat the default. Named arguments solve that.

Careful with array defaults

An array default is fine, because PHP copies it for each call.

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

print_r(addTag("php"));
print_r(addTag("web"));
Output
OUTPUT
Array
(
    [0] => php
)
Array
(
    [0] => web
)
lightbulb
Use defaults for settings
Options like $limit = 10 or $separator = "," are perfect defaults. A value that every caller must decide should stay a required parameter.