PHP Function with Optional Parameters

PhpFunctionParameter Passing

Php Problem Overview


I've written a PHP function that can accept 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?

Php Solutions


Solution 1 - Php

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();
  }
}

Solution 2 - Php

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

Solution 3 - Php

To accomplish what you want, use an array Like Rabbot said (though this can become a pain to document/maintain if used excessively). Or just use the traditional optional args.

//My function with tons of optional params
function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
{
  //Do stuff
}
my_func('Hi', 'World', null, null, 'Red');

However, I usually find that when I start writing a function/method with that many arguments - more often than not it is a code smell, and can be re-factored/abstracted into something much cleaner.

//Specialization of my_func - assuming my_func itself cannot be refactored
function my_color_func($reg_a, $reg_b, $opt = 'Red')
{
  return my_func($reg_a, $reg_b, null, null, $opt);
}
my_color_func('Hi', 'World');
my_color_func('Hello', 'Universe', 'Green');

Solution 4 - Php

You can just set the default value to null.

<?php
function functionName($value, $value2 = null) {
// do stuff
}

Solution 5 - Php

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example Using ... to access variable arguments

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

10

Variable-length argument lists PHP Documentation

Solution 6 - Php

NOTE: This is an old answer, for PHP 5.5 and below. PHP 5.6+ supports default arguments

In PHP 5.5 and below, you can achieve this by using one of these 2 methods:

  • using the func_num_args() and func_get_arg() functions;
  • using NULL arguments;

How to use

function method_1()
{
  $arg1 = (func_num_args() >= 1)? func_get_arg(0): "default_value_for_arg1";
  $arg2 = (func_num_args() >= 2)? func_get_arg(1): "default_value_for_arg2";
}

function method_2($arg1 = null, $arg2 = null)
{
  $arg1 = $arg1? $arg1: "default_value_for_arg1";
  $arg2 = $arg2? $arg2: "default_value_for_arg2";
}

I prefer the second method because it's clean and easy to understand, but sometimes you may need the first method.

Solution 7 - Php

Starting with PHP 8 you are able to use named arguments:

function namedParameters($paramOne, $paramTwo, $paramThree = 'test', $paramFour = null)
{
    dd($paramOne, $paramTwo, $paramThree, $paramFour);
}

We can now call this function with the required params and only the optinal params, that we want to differ from the default value which we specified in the function.

namedParameters('one', 'two', paramFour: 'four');

Result:

// "one", "two", "test", "four"

Solution 8 - Php

I think, you can use objects as params-transportes, too.

$myParam = new stdClass();
$myParam->optParam2 = 'something';
$myParam->optParam8 = 3;
theFunction($myParam);

function theFunction($fparam){      
  return "I got ".$fparam->optParam8." of ".$fparam->optParam2." received!";
}

Of course, you have to set default values for "optParam8" and "optParam2" in this function, in other case you will get "Notice: Undefined property: stdClass::$optParam2"

If using arrays as function parameters, I like this way to set default values:

function theFunction($fparam){
   $default = array(
      'opt1' => 'nothing',
      'opt2' => 1
   );
   if(is_array($fparam)){
      $fparam = array_merge($default, $fparam);
   }else{
      $fparam = $default;
   }
   //now, the default values are overwritten by these passed by $fparam
   return "I received ".$fparam['opt1']." and ".$fparam['opt2']."!";
}

Solution 9 - Php

If only two values are required to create the object with a valid state, you could simply remove all the other optional arguments and provide setters for them (unless you dont want them to changed at runtime). Then just instantiate the object with the two required arguments and set the others as needed through the setter.

Further reading

Solution 10 - Php

I know this is an old post, but i was having a problem like the OP and this is what i came up with.

Example of array you could pass. You could re order this if a particular order was required, but for this question this will do what is asked.

$argument_set = array (8 => 'lots', 5 => 'of', 1 => 'data', 2 => 'here');

This is manageable, easy to read and the data extraction points can be added and removed at a moments notice anywhere in coding and still avoid a massive rewrite. I used integer keys to tally with the OP original question but string keys could be used just as easily. In fact for readability I would advise it.

Stick this in an external file for ease

function unknown_number_arguments($argument_set) {
   
	foreach ($argument_set as $key => $value) {

		# create a switch with all the cases you need. as you loop the array 
		# keys only your submitted $keys values will be found with the switch. 
		switch ($key) {
			case 1:
				# do stuff with $value
				break;
			case 2:
				# do stuff with $value;
				break;
			case 3:
				# key 3 omitted, this wont execute 
				break;
			case 5:
				# do stuff with $value;
				break;
			case 8:
				# do stuff with $value;
				break;
			default:
				# no match from the array, do error logging?
				break;
		}
	}
return;
}

put this at the start if the file.

$argument_set = array(); 

Just use these to assign the next piece of data use numbering/naming according to where the data is coming from.

$argument_set[1][] = $some_variable; 

And finally pass the array

unknown_number_arguments($argument_set);

Solution 11 - Php

function yourFunction($var1, $var2, $optional = Null){
   ... code
}

You can make a regular function and then add your optional variables by giving them a default Null value.

A Null is still a value, if you don't call the function with a value for that variable, it won't be empty so no error.

Solution 12 - Php

If you are commonly just passing in the 8th value, you can reorder your parameters so it is first. You only need to specify parameters up until the last one you want to set.

If you are using different values, you have 2 options.

One would be to create a set of wrapper functions that take different parameters and set the defaults on the others. This is useful if you only use a few combinations, but can get very messy quickly.

The other option is to pass an array where the keys are the names of the parameters. You can then just check if there is a value in the array with a key, and if not use the default. But again, this can get messy and add a lot of extra code if you have a lot of parameters.

Solution 13 - Php

PHP allows default arguments (link). In your case, you could define all the parameters from 3 to 8 as NULL or as an empty string "" depending on your function code. In this way, you can call the function only using the first two parameters.

For example:

<?php
  function yourFunction($arg1, $arg2, $arg3=NULL, $arg4=NULL, $arg5=NULL, $arg6=NULL, $arg7=NULL, $arg8=NULL){
echo $arg1;
echo $arg2;
if(isset($arg3)){echo $arg3;}
# other similar statements for $arg4, ...., $arg5
if(isset($arg8)){echo $arg8;}
}

Solution 14 - Php

Just set Null to ignore parameters that you don't want to use and then set the parameter needed according to the position.

 function myFunc($p1,$p2,$p3=Null,$p4=Null,$p5=Null,$p6=Null,$p7=Null,$p8=Null){
    for ($i=1; $i<9; $i++){
        $varName = "p$i";
        if (isset($$varName)){
            echo $varName." = ".$$varName."<br>\n";
        }
    }
}   

myFunc( "1", "2", Null, Null, Null, Null, Null, "eight" );

Solution 15 - Php

func( "1", "2", default, default, default, default, default, "eight" );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser481826View Question on Stackoverflow
Solution 1 - PhpRabbottView Answer on Stackoverflow
Solution 2 - PhpMatt BallView Answer on Stackoverflow
Solution 3 - PhpKayla RoseView Answer on Stackoverflow
Solution 4 - PhpBlake StevensonView Answer on Stackoverflow
Solution 5 - PhpMentos1386View Answer on Stackoverflow
Solution 6 - PhpDaniel LoureiroView Answer on Stackoverflow
Solution 7 - PhpMatthiasView Answer on Stackoverflow
Solution 8 - PhppsadView Answer on Stackoverflow
Solution 9 - PhpGordonView Answer on Stackoverflow
Solution 10 - PhpCodingInTheUKView Answer on Stackoverflow
Solution 11 - Phpantoine serryView Answer on Stackoverflow
Solution 12 - PhpAlan GeleynseView Answer on Stackoverflow
Solution 13 - PhpAndrés LunaView Answer on Stackoverflow
Solution 14 - PhpFERNANDO BARAZZETTIView Answer on Stackoverflow
Solution 15 - PhpFlinschView Answer on Stackoverflow