tolkinski
tolkinski

Reputation: 290

Declaring an optional array argument

I was wondering if there is any difference when setting default array value to be an empty array or NULL.

For example:

function arrayTest(array $array = array()) {
    if(!empty($array)) {
        // Do something
    }
}

or

function arrayTest(array $array = NULL) {
    if(!empty($array)) {
        // Do something
    }
}

What I noticed is that the first example doesn't allow NULL values to be passed and the second example does, because of type-casting.

Are there any other differences?

Upvotes: 2

Views: 6026

Answers (2)

GolezTrol
GolezTrol

Reputation: 116110

Specifying = null will indeed allow you to pass null as an argument. But another difference is that if you don't pass an argument at all, it will default to array() or null, which are two very distinct values. You can check for that of course, but you will need to take it into account. empty will work for both, but a foreach loop over null won't work that well, and various array functions will also fail.

Until PHP 7.1 you could only pass null to a type hinted argument if you added = null to the declaration, making null the default value.

That was not only true for arrays but for objects as well. And as a side effect of specifying this default value, it would also be possible to invoke the function without specifying an argument at all, which is not always desirable.

Since version 7.1, PHP supports type hinting for nullable arguments and return values, so you can now write:

function arrayTest(?array $array) {

}

In this case the parameter is nullable (you can pass null to this function). But it's still mandatory to specify the argument explicitly; omitting the parameter is an error.

If to you there is no logical difference between an empty array or null, I would choose the first method of defaulting to an empty array. Then at least you'll know that the input is always an array. I think that add clarity to both the implementer of the function and the programmer(s) who use it. But I guess that's just an opinion and not even a strong one.

My main advice would be to not make the argument optional at all. In my experience this will make the usage of such functions unclear, especially as the code grows and more arguments are added.

Upvotes: 7

Dharman
Dharman

Reputation: 33239

Your observation is correct. These are two different things. One allows null as a value and the other doesn't.

This is an old and deprecated syntax:

function arrayTest(array $array = NULL) {

It is equivalent to this:

function arrayTest(array|null $array = NULL) { // Or ?array

You should only allow null as a value when it is something you expect. If your function doesn't expect $array to be null then you should only use array as the type and use an empty array as a default value.

Upvotes: 1

Related Questions