3

Possible Duplicate:
Any way to specify optional parameter values in PHP?
PHP function - ignore some default parameters

Suppose I have function like this:

function foo($name = "john", $surname = "smith") { ... }

And I am calling like this:

$test = foo("abc", "def");

Imagine now that I would like to skip the name and only use the surname, how is that achievable? If I only do $test = foo("def"); how can the compiler know I am referring to the surname and not to the name? I understand it could be done by passing NULL, but I need this for something more like this:

$test = foo($_POST['name'], $_POST['surname']);

Thanks in advance.

Community
  • 1
  • 1
john smith
  • 565
  • 1
  • 10
  • 20
  • possible duplicate of [PHP function - ignore some default parameters](http://stackoverflow.com/questions/9541776/php-function-ignore-some-default-parameters). See also [Is it possible to omit random parameters in a function call?](http://stackoverflow.com/questions/14120071/is-it-possible-to-omit-random-parameters-in-a-function-call) – Álvaro González Jan 02 '13 at 13:24

4 Answers4

3

You can try this-

$num_args = func_num_args();
if($num_args == 1)
 $surname = func_get_arg(1);
else
 $surname = func_get_arg(2);
 $name = func_get_arg(1);

Please test it before you use it.

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
2

Your code

$test = foo($_POST['name'], $_POST['surname']);

will also pass NULL in the first PARAMETER if it is empty so the compiler will know that it is up to the second parameter. Having a comma in the parameter list will already inform PHP that there are two parameters here.

Zevi Sternlicht
  • 5,399
  • 19
  • 31
0

You can do so by passing an empty string to your function and detecting in your function if the passed argument is an empty string, and if it is, then replacing it by the default value. this would make your function call like:

foo('','lastname');

And you can add these few lines to beginning of your function to detect if an empty string has been passed as a parameter:

function foo($name = "john", $surname = "smith") { 
    if($name==='') { $name = 'john'}
    //more code 
    ... }
Peeyush Kushwaha
  • 3,453
  • 8
  • 35
  • 69
0

I usually do something like so:

function foo($parameters = array())
{
    print_r($parameters);
}

foo($_POST); //will output the array

It's what I use, when I expect more than 3 parameters.

But you might as well use the following:

function foo()
{
    $args = func_get_args();  
    foreach ($args as $arg) {  
        echo "$arg \n";  
    }
}
Alex
  • 7,538
  • 23
  • 84
  • 152