PHP Default Arguments
In this page:
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
function greet($name = 'Guest') {
echo "Hello, $name!";
}
greet();
?>
Login to try C/C++/Java/PHP code in the editor
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
function greet($name, $greeting = "Hello") {
echo "$greeting, $name!";
}
greet("Alice");
?>
Login to try C/C++/Java/PHP code in the editor
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
function greet($name = 'Guest') {
echo "Hello, $name!";
}
greet("Alice");
?>
Login to try C/C++/Java/PHP code in the editor
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
function setVolume(int $level = 50) {
echo "Volume: $level";
}
setVolume();
?>
Login to try C/C++/Java/PHP code in the editor
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
function greet($name = 'Guest') {
$name = $name ?? 'Guest';
echo "Hello, $name!";
}
greet(null);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: