Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 26 / 68

Default Parameter Values

In this lesson you will learn how to give a PHP parameter a default value so callers can leave it out. This is for anyone searching for "PHP default parameter how to use".

Writing = value on a parameter sets a default that is used automatically when the caller omits that argument. Picture an order form where leaving a field blank gets you the usual house set.

The sample code defines function greet($name = "Guest"), so greet("Alice") uses the value passed while greet() falls back to the default "Guest".

A common stumbling block for beginners is that when several parameters have defaults, the ones without a default must come first. Writing function f($a, $b = "x", $c), with a defaulted parameter before a non-defaulted one, leads to behaviour you did not intend.

Letting callers omit arguments gives you a flexible function that serves both the simple case and the finely tuned one. In practice it is a favourite technique for functions with optional settings.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)