PHP get all arguments as array?

62,932

Solution 1

func_get_args returns an array with all arguments of the current function.

Solution 2

If you use PHP 5.6+, you can now do this:

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

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

source: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

Solution 3

Or as of PHP 7.1 you are now able to use a type hint called iterable

function f(iterable $args) {
    foreach ($args as $arg) {
        // awesome stuff
    }
}

Also, it can be used instead of Traversable when you iterate using an interface. As well as it can be used as a generator that yields the parameters.

Documentation

Share:
62,932
MiffTheFox
Author by

MiffTheFox

What am I even doing here?!

Updated on July 23, 2022

Comments

  • MiffTheFox
    MiffTheFox almost 2 years

    Hey, I was working with a PHP function that takes multiple arguments and formats them. Currently, I'm working with something like this:

    function foo($a1 = null, $a2 = null, $a3 = null, $a4 = null){
        if ($a1 !== null) doSomethingWith($a1, 1);
        if ($a2 !== null) doSomethingWith($a2, 2);
        if ($a3 !== null) doSomethingWith($a3, 3);
        if ($a4 !== null) doSomethingWith($a4, 4);
    }
    

    But I was wondering if I can use a solution like this:

    function foo(params $args){
        for ($i = 0; $i < count($args); $i++)
            doSomethingWith($args[$i], $i + 1);
    }
    

    But still invoke the function the same way, similar to the params keyword in C# or the arguments array in JavaScript.

  • Rob
    Rob about 15 years
    One gotcha with func_get_args that's worth pointing out; you can't pass it into another function call.
  • user3167101
    user3167101 over 14 years
    @Rob You can if you go $args = func_get_args() and then call_user_func_array($func, $args)
  • Aditya M P
    Aditya M P almost 13 years
    func_get_args() only returns values of those parameters that were PASSED to the function call, not all params defined in the function definition.
  • Francisco Corrales Morales
    Francisco Corrales Morales about 10 years
    can I do this: func_get_args('argument_name') ? to get the value of an argument.
  • Chris
    Chris almost 9 years
    @FranciscoCorralesMorales You can't get the value by argument name, but if you're fine with using the argument offset, you can use func_get_arg().
  • dr fu manchu
    dr fu manchu over 5 years
    This answer is outdated. Please see @joren 's answer