Give a parameter a default value and the caller may leave it out. That makes the argument optional.
<?php
function greet(string $name, string $greeting = "Hello"): string
{
return "$greeting, $name!";
}
echo greet("Mira") . "\n";
echo greet("Mira", "Welcome");
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.
<?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);
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.
<?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"]);
Limit 10, tags: 0
Limit 5, tags: 1
A null default
Use null when the real default needs to be calculated inside the function.
<?php
function formatDate(?string $date = null): string
{
$date ??= "today";
return "Date: $date";
}
echo formatDate() . "\n";
echo formatDate("2026-01-15");
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.
<?php
function addTag(string $tag, array $tags = []): array
{
$tags[] = $tag;
return $tags;
}
print_r(addTag("php"));
print_r(addTag("web"));
Array
(
[0] => php
)
Array
(
[0] => web
)
Use defaults for settings
$limit = 10 or $separator = "," are perfect defaults. A value that every caller must decide should stay a required parameter.