PHP Function with Optional Parameters

user481826 picture user481826 · Oct 20, 2010 · Viewed 199.6k times · Source

I've written a PHP function that can accepts 10 parameters, but only 2 are required. Sometimes, I want to define the eighth parameter, but I don't want to type in empty strings for each of the parameters until I reach the eighth.

One idea I had was to pass an abstracted function with an array of parameters which passes it along to the real function.

Is there a better way to set up the function so I can pass in only the parameters I want?

Answer

Rabbott picture Rabbott · Oct 20, 2010

What I have done in this case is pass an array, where the key is the parameter name, and the value is the value.

$optional = array(
  "param" => $param1,
  "param2" => $param2
);

function func($required, $requiredTwo, $optional) {
  if(isset($optional["param2"])) {
    doWork();
  }
}