210

In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads:

string date ( string $format [, int $timestamp = time() ] )

Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value.

How do you go about creating optional parameters like this when defining a custom function in PHP?

Syscall
  • 19,327
  • 10
  • 37
  • 52
gregh
  • 35,767
  • 9
  • 31
  • 27

7 Answers7

282

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}
jeremy
  • 9,965
  • 4
  • 39
  • 59
Jeff Winkworth
  • 4,874
  • 6
  • 34
  • 33
  • 5
    `function dosomething($var1, $var2, $optionalValue = null)` I found this better option. – Mohammad Zaid Pathan Aug 19 '19 at 14:31
  • 1
    setting the parameter to null would act like an optional argument. Setting the parameter to a value like this answer is doing is more like a default value than an 'optional' value. – briann Feb 28 '23 at 08:44
56

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

Ross
  • 46,186
  • 39
  • 120
  • 173
  • 1
    however, this will evaluate if 0 or "false" was passed to $bar. – Tyzoid Jan 04 '13 at 02:02
  • 42
    Null is a much better default. – Kzqai Apr 07 '13 at 16:23
  • 3
    @DooMMasteR, here, you mean `$bar === false` - this is an action that should be done when `$bar` has defaulted to `false`. This will avoid incorrect action if `0` is passed in, so it does work - UNLESS a boolean is needed. As Kzqai said, a more general solution is to use `$bar = null`, because that can also be used when the values of $bar are boolean. The test then becomes `if (is_null($bar))` or `if ($bar === null)`. – ToolmakerSteve Aug 17 '16 at 13:48
23

Some notes that I also found useful:

  • Keep your default values on the right side.

    function whatever($var1, $var2, $var3="constant", $var4="another")
    
  • The default value of the argument must be a constant expression. It can't be a variable or a function call.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
gregh
  • 35,767
  • 9
  • 31
  • 27
15

The date function would be defined something like this:

function date($format, $timestamp = null)
{
    if ($timestamp === null) {
        $timestamp = time();
    }

    // Format the timestamp according to $format
}

Usually, you would put the default value like this:

function foo($required, $optional = 42)
{
    // This function can be passed one or more arguments
}

However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.

Lars Gyrup Brink Nielsen
  • 3,939
  • 2
  • 34
  • 35
15

Give the optional argument a default value.

function date ($format, $timestamp='') {
}
mk.
  • 26,076
  • 13
  • 38
  • 41
12

If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).

Syntax:

function <functionName> ([<type> ]...<$paramName>) {}

For example:

function someVariadricFunc(...$arguments) {
  foreach ($arguments as $arg) {
    // do some stuff with $arg...
  }
}

someVariadricFunc();           // an empty array going to be passed
someVariadricFunc('apple');    // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');

As you can see, this token basically turns all parameters to an array, which you can process in any way you like.

Gergely Lukacsy
  • 2,881
  • 2
  • 23
  • 28
8

Starting with 7.1 there is a type hinting for nullable parameters

function func(?Object $object) {}

It will work for these cases:

func(null); //as nullable parameter
func(new Object());  // as parameter of declared  type

But for optional value signature should look like.

function func(Object $object = null) {} // In case of objects
function func(?Object $object = null) {} // or the same with nullable parameter

function func(string $object = '') {} // In case of scalar type - string, with string value as default value
function func(string $object = null) {} // In case of scalar type - string, with null as default value
function func(?string $object = '') {} // or the same with nullable parameter

function func(int $object = 0) {} // In case of scalar type - integer, with integer value as default value
function func(int $object = null) {} // In case of scalar type - integer, with null as default value
function func(?int $object = 0) {} // or the same with nullable parameter

than it can be invoked as  

func(); // as optional parameter
func(null); // as nullable parameter
func(new Object()); // as parameter of declared type
Arkadii Chyzhov
  • 191
  • 1
  • 4