php
  1. php-default-arguments

PHP Default Arguments

Default arguments are useful while defining a function. In PHP, we can specify a default value to an argument by simply assigning a value to the argument, and if the value is not passed, it will take the default value.

Syntax

function function_name(argument1 = value1, argument2 = value2, ..., argumentN = valueN) {
   //function code;
}

Example

function greet($name = "John") {
   echo "Hello, $name!";
}

//function is called without an argument
greet(); // Output: Hello, John!

//function is called with an argument
greet("Jane"); // Output: Hello, Jane!

Output

Hello, John!
Hello, Jane!

Explanation

In the above code, we have created a function greet() which takes an argument $name. We have assigned a default value "John" to the $name argument. When we call the greet() function without any argument, it will take the default value "John". When we call the greet() function with the argument "Jane", it will take the passed value.

Use

  • It is useful when you want to avoid errors or exceptions while calling a function without passing an argument.
  • It is useful when you want to set a default value to an argument when the value is not passed.

Important Points

  • Default argument values must be a constant expression.
  • Default argument values must be at the end of the argument list.

Summary

In PHP, we can define a default value to the function arguments. If the value is not passed, it will take the default value. It is useful when you want to avoid errors or exceptions while calling a function without passing an argument. Default argument values must be a constant expression, and they must be at the end of the argument list.

Published on: