0
0
PHPprogramming~5 mins

Default parameter values in PHP

Choose your learning style9 modes available
Introduction

Default parameter values let you give a function a backup value to use if no value is given when calling it.

When you want a function to work even if some inputs are missing.
When you want to avoid errors from missing arguments.
When you want to set common or typical values automatically.
When you want to make your function easier to use with fewer inputs.
Syntax
PHP
function functionName($param1 = defaultValue1, $param2 = defaultValue2) {
    // function body
}

Default values must come after parameters without defaults.

You can use any valid value as a default, like numbers, strings, or arrays.

Examples
This function says hello to a name. If no name is given, it uses "Friend".
PHP
<?php
function greet($name = "Friend") {
    echo "Hello, $name!";
}
?>
This function adds two numbers. If the second number is missing, it adds 10.
PHP
<?php
function add($a, $b = 10) {
    return $a + $b;
}
?>
Sample Program

This program defines a function that describes a pet with default type "dog" and name "Buddy". It calls the function three times: with no arguments, with one argument, and with two arguments.

PHP
<?php
function describePet($type = "dog", $name = "Buddy") {
    echo "I have a $type named $name.";
}

describePet();
echo "\n";
describePet("cat");
echo "\n";
describePet("parrot", "Polly");
?>
OutputSuccess
Important Notes

Always put parameters with default values after those without defaults.

If you call a function without some arguments, PHP uses the default values automatically.

Summary

Default parameter values make functions flexible and easier to use.

They help avoid errors when arguments are missing.

Use them by assigning a value in the function definition.