2

I'm still new to PHP, so I wonder if it is possible to write a function with several optional parameters but at least one of those needs to be used?

Something like

function my_func($arg1="", $arg2="", $arg3=""){
//at least one of the args should be set
}

or do I just test within in the function and return false if none was set?

1
  • You can set default values for 2 of them Commented Feb 1, 2021 at 7:55

3 Answers 3

2

You could add code yourself which you can always enhance to check (for example) only 1 argument should be passed. Just throw InvalidArgumentException with some description if the validation fails...

function my_func($arg1="", $arg2="", $arg3=""){
    if ( empty($arg1) && empty($arg2) && empty($arg3) ) {
        throw new InvalidArgumentException("At least one parameter must be passed");
    }
}

You may want to set the default values to null if "" is a valid value, but then change the test to is_null($arg1) etc. as "" is also empty.

Sign up to request clarification or add additional context in comments.

Comments

2

You should check it manually. Like this

function my_func($arg1="", $arg2="", $arg3=""){
 if (!$arg1 && !$arg2 && !$arg3) {
   throw new Exception('None of arguments is set!'); //Or just return false, depend on your siruation
 }
 //...
}

Comments

2

You would have to explicitly check it within the function body, but you can streamline it a little by pushing all your variables to an array, and filter the empty values out. When there are no results left after filtering, you know none was passed.

function my_func($arg1 = null, $arg2 = null, $arg3 = null) {
    if (count(array_filter([$arg1, $arg2, $arg3])) === 0) {
        throw new InvalidArgumentException('At least one argument must be used');
    }
    echo 'It works!'."\n";
}

2 Comments

no need to count if (array_filter([$arg1, $arg2, $arg3]) === []) {
Using count you can alter the logic to ensure exactly 1 argument was passed, by changing it to !== 1 instead of === 0. But yes, either works - I prefer using count.

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.