18

Is it possible to use an array as a default parameter in a PHP function?

I would like to do the following:

$arr = array(1,2,3,4);

function sample($var1, $var2, $var3 = $arr){
    echo $var1.$var2;
    print_r($var3);
}

sample('a','b');
// Should still work without the third parameter and default to $arr
1
  • 3
    No, $var3 = array(1,2,3,4) would work though. Commented Jan 22, 2013 at 10:46

4 Answers 4

26

No, this is not possible, the right hand expression of the default value must be a constant or array literal, i.e.

function sample($var1, $var2, $var3 = array(1, 2, 3, 4))
{
}

If you want this behaviour, you could use a closure:

$arr = array(1, 2, 3, 4);

$sample = function ($var1, $var2, array $var3 = null) use ($arr) {
    if (is_null($var3)) {
        $var3 = $arr;
    }

    // your code
}

$sample('a', 'b');

You could also express it with a class:

class Foo
{
    private static $arr = array(1, 2, 3, 4);

    public static function bar($var1, $var2, array $var3 = null)
    {
        if (is_null($var3)) {
            $var3 = self::$arr;
        }

        // your code here
    }
}

Foo::bar('a', 'b');
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the detailed answer! Is the array in test($var1, $var2, array $var3 = null) valid notation? Never seen that before!
I come from a JavaScript background so PHP classes are a little strange to me, so I definitely prefer the closure!
@jasdeepkhalsa It's valid, the passed value must either be an array or the default value null.
@jasdeepkhalsa The class example is like Sample = { arr: [1,2,3,4], test: function(v1, v2, v3) { v3 = v3 || this.arr }}
@JaeGeeTee The argument is either an array or null, so that should answer your question :)
|
7

You can't pass $arr into the function definition, you'll have to do:

function sample($var1, $var2, $var3 = array('test')){
    echo $var1.$var2;
    echo print_r($var3);
}

sample('a','b'); // output: abArray ( [0] => test ) 1

or, if you want to be really dirty (I wouldn't recommend it..):

$arr = array('test');

function sample($var1, $var2, $var3 = null){
    if($var3 == null){
      global $arr;
      $var3 = $arr;
    }
    echo $var1.$var2;
    echo print_r($var3);
}

sample('a','b');

Comments

5

(It might not be a complete answer, but it covers some useful cases.)

If you want to get one or more options using an array as an argument in a function (or a method), setting a default set of options might not help. Instead, you can use array_replace().

For example, let's consider a sample $options argument which gets an array with two keys, count and title. Setting a default value for that argument leads overriding it when using the function with any custom $option value passed. In the example, if we set $options to have only one count key, then the title key will be removed. One of the right solutions is the following:

function someCoolFunc($options = []) {
    $options = array_replace([
        "count" => 144,
        "title" => "test"
    ], $options);
    
    // ... 
}

In the example above, you will be ensured that count and title indexes are present, even if the user supplies an empty array (keep in mind, the order of the arguments in array_replace() function is important).

Note: In the explained case, using a class (or interface) is also an option, but one reason to choose arrays over it might be simplicity (or even performance).

Comments

0

I tried the last example above. Here was my comparable test:

function someFunc($options = [])
    {
        $options = array_replace([
            "<br>", "<b>", "<i>", "<u>", "<hr>", "<span>"
        ], $options);
        print_r($options);
    }

here is the result:

>>> somefunc()
Array
(
    [0] => <br>
    [1] => <b>
    [2] => <i>
    [3] => <u>
    [4] => <hr>
    [5] => <span>
)
=> null

Yet looks what happens when you try to add a tag. Notice what happens to the original values. Element [0] is changed. The array is not added to:

>>> someFunc(["<div>"])
Array
(
    [0] => <div>
    [1] => <b>
    [2] => <i>
    [3] => <u>
    [4] => <hr>
    [5] => <span>
)
=> null

This would allow you to add an element to default option:

function someFunc($options = array())
    {
       array_push($options, "<br>", "<b>", "<i>", "<u>", "<hr>", "<span>");
       return $options;
    }

Here is what results:

>>> someFunc()
=> [
     "<br>",
     "<b>",
     "<i>",
     "<u>",
     "<hr>",
     "<span>",
   ]

---
 someFunc(["<div>","<table>"]);
=> [
     "<div>",
     "<table>",
     "<br>",
     "<b>",
     "<i>",
     "<u>",
     "<hr>",
     "<span>",
   ]

this way, the default values get added to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.