Print the keys of an array

前端 未结 8 706
旧巷少年郎
旧巷少年郎 2020-11-27 21:07

I could not figure out how to pass a variable number of variables into a function. I thought passing in an array and using the array keys for the variables names could repla

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 21:21

    I'm sure there is a better way to accomplish this, suggestions welcome

    Because you asked for alternate suggestions, here's one. You can use varargs to pass a variable number of arguments to a function. Here's an example:

    function my_function() {
        $numArgs = func_num_args();
        $args = func_get_args(); // an array of the arguments, in order
    }
    

    This doesn't offer you "named" arguments, but it does allow you variable numbers of arguments (like you claim you're trying to do in your question).

    Here are some relevant documentation pages:

    • func_get_args()
    • func_get_arg()
    • func_num_args()

    However, that's not to say that your array-based approach is a bad one. In some ways it provides batter readability since you're explicitly mapping keys to values; maintainers reading your code will be better-able to understand what's being passed to the function. I'm just giving you some options.

提交回复
热议问题