- PHP: Using optional default parameters in a function.
- Example of a PHP function that has default arguments.
- Multiple default parameters.
- Function with optional parameters php
- PHP Function with Optional Parameters
- Optional parameters in PHP function without considering order
- Passing an optional parameter in PHP Function
- How do you create optional arguments in php?
- Any way to specify optional parameter values in PHP?
- PHP optional parameter
- Using Default Arguments in a Function
- 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?
- Optional Parameter
- Multiple optional argument in a function
PHP: Using optional default parameters in a function.
This is a guide on how to use optional / default function parameters in PHP. In other languages such as Java, you can use a feature called Method Overloading. However, in PHP, two functions cannot have the same name.
Optional parameters are useful because they allow us to control how a function is executed if a certain parameter has been omitted from the function call.
Example of a PHP function that has default arguments.
Let’s take a look at the following example:
/** * A function that returns an array * of animals. * * @param bool $sort Optional parameter. * @return array */ function getAnimals($sort = false) < $animalsArray = array( 'Dog', 'Cat', 'Zebra', 'Horse' ); if($sort === true)< sort($animalsArray); >return $animalsArray; >
The function above has one parameter called $sort. By default, $sort is set to a boolean FALSE value. As a result, our $sort parameter will default to FALSE if the getAnimals function is called without any arguments.
You can test this out by running the following PHP snippet:
//Calling the function without specifying //the default parameter. $animals = getAnimals(); var_dump($animals); //Calling the function with the //default parameter. $animals = getAnimals(true); var_dump($animals);
In the first function call, we omitted the first parameter. This means that $sort will default to FALSE:
As you can see, the array above has not been sorted.
However, in the second function call, we did provide an argument. This means that our default parameter is overridden:
In the screenshot above, you can see that the array has been sorted in alphabetical order.
Multiple default parameters.
PHP functions can have multiple default parameters. Take the following example:
//Example of a PHP function that has multiple //default parameters function my_function($a = false, $b = true, $c = null)< //do something >
The PHP function above has three parameters, all of which have their own default values:
- $a has a default value of FALSE.
- $b has been set to TRUE.
- $c is NULL by default.
As a result, you can call the function above like so:
//Calling the function without providing //any parameters. my_function();
You can also provide only one of the three optional arguments:
//Only providing the first parameter. my_function(true);
The function call above will result in the first parameter $a being set to TRUE.
But what if we only wanted to change the last optional argument? Well, in that case, we need to provide all of the function’s arguments while making sure that the default values of the first two parameters aren’t changed:
//Changing the last parameter. my_function(false, true, 'test');
In the example above, we used the default values of the first two parameters while changing the third.
Hopefully, you found this tutorial useful!
Function with optional parameters php
To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.
#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>
$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );
$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;
/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us
3 valuue yes 129 s
4 reference yes 66 us
1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]
2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)
3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)
5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>
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
function test($required, $optional = NULL)
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:
- 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.
- 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.
- Pass a null value to any argument you don’t want to specify. Not really getting around it, but it works.
- 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:
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
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