CodeBlanks Logo Icon CodeBlanks

Default parameter values

PHP course · Beginner · Lesson 78/116

Learn to assign a default value to a parameter so it can be skipped at the call.

Default value

You can assign a default value to a parameter. This is the value used when the caller skips that argument. The assignment uses = inside the parentheses.

Example: function greet($name = "Guest") { echo $name; }. The call greet("Alex") prints "Alex"; the call greet() passes no argument, so the default "Guest" is used and "Guest" is printed.

Optional parameter

Parameters with a default are optional: the caller may skip them. This is handy for values that are the same in most calls.

For example in function logMessage($msg, $level = "INFO") { echo "[" . $level . "] " . $msg; } the $level is optional. The call logMessage("Started") skips $level and uses "INFO"; the call logMessage("Error", "ERROR") passes "ERROR" to $level. Optional parameters must always come after required ones.

Exercise Print a log message

Define a function logMessage with parameters $msg and $level = "INFO". In the body write echo "[" . $level . "] " . $msg . "\n";. Then call logMessage("System started") first and logMessage("Connection lost", "ERROR") second.

Show example solution
Define function logMessage($msg, $level = "INFO") { ... }, put echo "[" . $level . "] " . $msg . "\n"; in the body. The first call takes one argument logMessage("System started");, the second takes two logMessage("Connection lost", "ERROR");.
Example solution:
<?php
// Define logMessage and call it twice
function logMessage($msg, $level = "INFO") {
    echo "[" . $level . "] " . $msg . "\n";
}
logMessage("System started");
logMessage("Connection lost", "ERROR");

Test yourself

  1. Complete the default value

    function greet($name____) { echo $name; }
    Show answer
    function greet($name = "Guest") { echo $name; }
  2. What is the output of the following code?

    function greet($name = "Guest") {
        echo $name;
    }
    greet();
    • $name
    • (empty output)
    • Guest
    • PHP error
    Show answer

    Guest — Correct. With no argument passed, $name takes its default 'Guest'.

  3. Match default value concepts

    Default value
    Used when no argument is passed
    $name = "Guest"
    Default value syntax
    Optional
    A parameter with a default

All lessons in Beginner