Compare these functions, is there a benefit to using null as a default argument

One function has $toPage = null as the argument, the other function just uses $toPage. Why use null?


function redirect_page($toPage = null){
        if ($toPage != null){
            header("Location:".$toPage);
            die();
        }
    }

function redirect_page($toPage){
        header("Location:".$toPage);
        die();
    }

It depends on how the function is used and what is being passed in.

Considering that there’s only one argument being passed, I might not opt to include a default value if there is a check/filter for input elsewhere.

If there were multiple arguments which might not always have a value, then it might be more appropriate to assign a default value like that.

Understood. Thanks.

Is it true that with multiple arguments, if one or more arguments have a default value of null that it must be last in the argument list?

i.e.


function example($value1, $value2 = null){
        
    }

if not is there any situation where this is necessary?

Typically, optional arguments are placed last so that when the function is called, you could just call it with the required argument and leave out the optional argument (the one with an existing default value): example(“value_a”)

There’s no rule preventing you from actually changing the order, but if you did, then you would have to call the function with both arguments or the function call wouldn’t work properly. Example:

function example(value2=null, value1){}
example("value_b","value_a");

Also, see example #5 here: PHP: Function arguments - Manual