PHP Function with Optional Parameters

PHP Function with Optional Parameters

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.

Optional parameters in PHP function without considering order

This is modified from one of the answers and allows arguments to be added in any order using associative arrays for the optional arguments

 function createUrl($host, $path, $argument = []){
$optionalArgs = [
'protocol'=>'http',
'port'=>80];
if( !is_array ($argument) ) return false;
$argument = array_intersect_key($argument,$optionalArgs);
$optionalArgs = array_merge($optionalArgs,$argument);
extract($optionalArgs);
return $protocol.'://'.$host.':'.$port.'/'.$path;
}

//No arguments with function call
echo createUrl ("www.example.com",'no-arguments');
// returns http://www.example.com:80/no-arguments

$argList=['port'=>9000];
//using port argument only
echo createUrl ("www.example.com",'one-args', $argList);
//returns http://www.example.com:9000/one-args

//Use of both parameters as arguments. Order does not matter
$argList2 = ['port'=>8080,'protocol'=>'ftp'];
echo createUrl ("www.example.com",'two-args-no-order', $argList2);
//returns ftp://www.example.com:8080/two-args-no-order

Passing an optional parameter in PHP Function

try this:

function test($required, $optional = NULL){..} 

then you can call

test($required, $optional)

and with $optional null

test($required);  

How do you create optional arguments in php?

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}

Any way to specify optional parameter values in PHP?

PHP does not support named parameters for functions per se. However, there are some ways to get around this:

  1. Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array.
  2. If you want to allow optional number of arguments depending on context, then you can use func_num_args and func_get_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do.
  3. Pass a null value to any argument you don't want to specify. Not really getting around it, but it works.
  4. If you're working in an object context, then you can use the magic method __call() to handle these types of requests so that you can route to private methods based on what arguments have been passed.

PHP optional parameter

That's because the $param = 'value' bit in the function declaration is not executed every time the function is called.

It only comes into play if you don't pass a value for that parameter.

Instead of reading it as a literal assignment PHP does something along the lines of the following under the hood whenever it enters your function.

if true === $param holds no value
$param = 'value'
endif

In other words, $param = 'value' is not a literal expression within the context of the language but rather a language construct to define the desired behaviour of implementing fallback default values.

Edit: Note that the snippet above is deliberately just pseudo code as it's tricky to accurately express what's going using PHP on once PHP has been compiled. See the comments for more info.

Using Default Arguments in a Function

I would propose changing the function declaration as follows so you can do what you want:

function foo($blah, $x = null, $y = null) {
if (null === $x) {
$x = "some value";
}

if (null === $y) {
$y = "some other value";
}

code here!

}

This way, you can make a call like foo('blah', null, 'non-default y value'); and have it work as you want, where the second parameter $x still gets its default value.

With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.

As stated in other answers,

default parameters only work as the last arguments to the function.
If you want to declare the default values in the function definition,
there is no way to omit one parameter and override one following it.

If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.

Here is another example (this doesn't answer your question, but is hopefully informative:

public function __construct($params = null)
{
if ($params instanceof SOMETHING) {
// single parameter, of object type SOMETHING
} elseif (is_string($params)) {
// single argument given as string
} elseif (is_array($params)) {
// params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
} elseif (func_num_args() == 3) {
$args = func_get_args();

// 3 parameters passed
} elseif (func_num_args() == 5) {
$args = func_get_args();
// 5 parameters passed
} else {
throw new \InvalidArgumentException("Could not figure out parameters!");
}
}

How to only pass an optional parameter to a PHP function by keeping all other mandatory/optional parameters(if any) equal to their default values?

Passing '' does not mean falling back to default argument value. It means just that — trying to pass an empty string.

You would need to reproduce defaults if you want to achieve this:

htmlspecialchars('&', ENT_COMPAT | ENT_HTML401, ini_get('default_charset'), FALSE);

Optional Parameter

You must declare a parameter optional in the function parameters. It doesn't work because you have to told the PHP interpreter to expect a parameter.

function myFunc($param, $optional = null){
// ...
}

In PHP 7+ you can use the spread operator for argument unpacking to denote optional parameters. This is better than sending an array of arguments to a function.

function myFunc($param, ...$optional){
print_r($optional);
}

myFunc('baz'); // Array ( )
myFunc('baz', 'foo', 'foobar', 'whoo'); // Array ( [0] => foo [1] => foobar [2] => whoo )

Multiple optional argument in a function

You can try:

function getAllForms() {
extract(func_get_args(), EXTR_PREFIX_ALL, "data");
}

getAllForms();
getAllForms("a"); // $data_0 = a
getAllForms("a", "b"); // $data_0 = a $data_1 = b
getAllForms(null, null, "c"); // $data_0 = null $data_1 = null, $data_2 = c


Related Topics



Leave a reply



Submit