How to create optional arguments in PHP ?
In PHP, we can create optional arguments in a function by assigning a default value to the parameter. If the argument is not passed while calling the function, the default value will be used.
Here's an example:
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
greet(); // Output: Hello, Guest!
greet("John"); // Output: Hello, John!
In the above example, the greet()
function has an optional parameter $name
with a default value of "Guest". If the function is called without passing any argument, the default value will be used. If an argument is passed, it will override the default value.
We can also have multiple optional parameters in a function. Here's an example:
function calculate($num1, $num2 = 0, $operator = "+") {
switch($operator) {
case "+":
return $num1 + $num2;
case "-":
return $num1 - $num2;
case "*":
return $num1 * $num2;
case "/":
return $num1 / $num2;
default:
return "Invalid operator";
}
}
echo calculate(10); // Output: 10
echo calculate(10, 5); // Output: 15
echo calculate(10, 5, "-"); // Output: 5
In the above example, the calculate()
function has three parameters - $num1
, $num2
, and $operator
. $num2
and $operator
are optional parameters with default values of 0 and "+" respectively. If the function is called without passing $num2
and $operator
, their default values will be used. If only $num2
is passed, $operator
will have its default value. If both $num2
and $operator
are passed, they will override their default values.