← Back to PHP Course | Chapter 5: Functions | Lesson 4 of 10

PHP Default Arguments

What are Default Arguments?

Assigning a value directly in a parameter's definition (function greet($name = Guest)) makes that argument optional at the call site — if the caller doesn't supply one, PHP quietly falls back to the default instead of raising an error about a missing argument.

Example: What are Default Arguments?

php
<?php
function greet($name = 'Guest') {
    echo "Hello, $name!";
}
greet();
?>

Placing Default Arguments

PHP requires every parameter that has a default value to come *after* every parameter that doesn't. Putting an optional parameter before a required one creates an ordering PHP can't resolve unambiguously, and it will refuse to parse the function definition at all.

Example: Placing Default Arguments

php
<?php
function greet($name, $greeting = "Hello") {
    echo "$greeting, $name!";
}
greet("Alice");
?>

Overriding Default Values

Calling the function normally and simply supplying a value overrides that parameter's default for that one call — defaults only ever apply when an argument is genuinely omitted, never when one is explicitly passed, even if it happens to match the default.

Example: Overriding Default Values

php
<?php
function greet($name = 'Guest') {
    echo "Hello, $name!";
}
greet("Alice");
?>

Type Declarations with Defaults

Type declarations and default values work together without conflict: PHP still validates the type of any value the caller actually supplies, while the default itself is exempt from that check (it's trusted as already correct when you wrote it).

Example: Type Declarations with Defaults

php
<?php
function setVolume(int $level = 50) {
    echo "Volume: $level";
}
setVolume();
?>

Null vs Default Argument

Explicitly passing null is treated as a real argument, not as 'nothing was passed' — it does *not* trigger the parameter's default value. If a parameter should genuinely fall back to its default on null too, that has to be handled inside the function body, not by the default-argument mechanism alone.

Example: Null vs Default Argument

php
<?php
function greet($name = 'Guest') {
    $name = $name ?? 'Guest';
    echo "Hello, $name!";
}
greet(null);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.