Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Get values of default arguments based on previous argument

I have a PHP function that takes three arguments, where one is an optional argument.

function theRange($min, $max) {
    // Function Body
}

But I have to set the limit to a default parameter and give it as an optional parameter. So, what I did is:

function theRange($min, $max = 5) {
    // Function Body
}

The problem comes when the $min is greater than 5 and the value becomes invalid if the maximum is lesser the the minimum value. So, I default the $max to $min, so what I did is:

function theRange($min, $max = $min) {
    // Function Body
}

This throws an error as below:

Parse error: syntax error, unexpected '$min' (T_VARIABLE) in functions.php on line 2.

I am currently handling it this way:

function theRange($min, $max = null) {
    if (!isset($max) || is_null($max))
         $max = $min;
    // Function Body
}

Is there a better way to handle this default parameter, to have the previous parameter as an input scenario? Thanks in advance! :)

Upvotes: 2

Views: 55

Answers (2)

C3roe
C3roe

Reputation: 96250

Can’t think of another way – but you could of course shorten that quite a bit using the ternary operator. And I think using isset makes no sense here at all – $max will always be set, because you specified it in the function parameters.

function theRange($min, $max = null) {
     $max = is_null($max) ? $min : $max;
    // Function Body
}

But you will still have to do additional checks anyway, because min=10 and max=5 could be passed explicitly to the function.

function theRange($min, $max = null) {
     $max = is_null($max) || $max < $min ? $min : $max;
    // Function Body
}

And depending on what that function is actually supposed to do, you might want to check for/exclude negative values as well …

Upvotes: 1

Maciej Jaśniaczyk
Maciej Jaśniaczyk

Reputation: 605

Simply assign default value, and check if it's valid inside function:

function theRange($min, $max = 5) {
    $max = $min > $max ? $min : $max;
}

Upvotes: 1

Related Questions