I have a function which takes two arguments but I want the second one to be optional:
function myFunction($arg1, $arg2) {
//blah
//blah
if (isset($arg2)) {
//blah
} else {
//blah
}
}
So when I call it, I might do myFunction("something") or I might do myFunction("something", "something else").
When I only include one argument, PHP gives this warning:
Warning: Missing argument 2 for myFunction(), …
So it works, but obviously the developers frown upon it.
Is it ok to do this or should I be passing in "" or false or 0 to the second argument when I don’t want to use it and testing for that instead of using isset()?
I’ve noticed that a lot of people miss out arguments when calling functions in JavaScript which is why I’m asking if it’s done in PHP too.
Its done by setting up some parameters as optional/giving it a default:
then you can call the function like this:
myFunction('something');or
myFunction('something', 'something else');