9

Possible Duplicate:
PHP get all arguments as array?

Well,

In java I can do this (pseudocode):

public hello( String..args ){
    value1 = args[0] 
    value2 = args[1] 
    ...
    valueN = arg[n];
}

and then:

hello('first', 'second', 'no', 'matter', 'the', 'size');

Is something like this in php?

EDIT

I now that I can pass an array like hello(array(bla, bla)), but may could exists the way mencioned above, right?

2

1 Answer 1

33

See func_get_args:

function foo()
{
    $numArgs = func_num_args();

    echo 'Number of arguments:' . $numArgs . "\n";

    if ($numArgs >= 2) {
        echo 'Second argument is: ' . func_get_arg(1) . "\n";
    }

    $args = func_get_args();
    foreach ($args as $index => $arg) {
        echo 'Argument' . $index . ' is ' . $arg . "\n";

        unset($args[$index]);
    }
}

foo(1, 2, 3);

EDIT 1

When you call foo(17, 20, 31) func_get_args() don't know that the first argument represents the $first variable for example. When you know what each numeric index represents you can do this (or similar):

function bar()
{
    list($first, $second, $third) = func_get_args();

    return $first + $second + $third;
}

echo bar(10, 21, 37); // Output: 68

If I want a specific variable, I can ommit the others one:

function bar()
{
    list($first, , $third) = func_get_args();

    return $first + $third;
} 

echo bar(10, 21, 37); // Output: 47
Sign up to request clarification or add additional context in comments.

9 Comments

you are so fast an furious :D It was what I am seaching for. Thank you! and the rest of people too
can I do this: func_get_args('argument_name') ? to get the value of an argument.
@FranciscoCorrales You can't. func_get_args() returns a numerical indexed array of arguments, not a variable list with corresponding pair.
@FranciscoCorrales see func_get_args examples
This answer is outdated. Since PHP 5.6 you can use Variable-length argument lists
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.