phparraysparametersargumentsassociative

How can I convert a PHP function's parameter list to an associative array?


I want to convert the arguments to a function into an associative array with keys equal to the parameter variable names, and values equal to the parameter values.

PHP:

function my_function($a, $b, $c) {

    // <--- magic goes here to create the $params array

    var_dump($params['a'] === $a); // Should result in bool(true)
    var_dump($params['b'] === $b); // Should result in bool(true)
    var_dump($params['c'] === $c); // Should result in bool(true)
}

How can I do this?


Solution

  • The you can do this using compact:

    function myFunc($a, $b, $c) {
        $params = compact('a', 'b', 'c');
        // ...
    }
    

    Or, get_defined_vars() will give you an associative array of all the variables defined in that scope, which would work, but I think this might also include $_POST, $_GET, etc...

    Otherwise, you can use func_get_args to get a list of all the arguments passed to the function. This is not associative though, since it is only data which is passed (that is, there's no variable names). This also lets you have any number of arguments in your function.

    Or, just specify one argument, which is an array:

    function myFunc($params) {
    
    }
    

    compact() seems to be closest to what you're after though.