Call function with (unknown) variable number of parameters?

青春壹個敷衍的年華 提交于 2019-12-10 17:38:40

问题


I'm need to send params to the function

array_intersect_key()

but sometimes i'm need to send 2 arrays, sometimes - 3 or more:

array_intersect_key($arr_1, $arr_2);
OR
array_intersect_key($arr_1, $arr_2, $arr_3, $arr_4);

回答1:


Assuming you want to create your own function like this, the key is to use func_get_args():

function mumble(){
    $args = func_get_args();
    foreach ($args as $arg){
        ... whatever
    }
}

If you just want to call it with multiple args, either "just do it", or use call_user_func_array():

$args = array();
... append args to $args
call_user_func_array('array_intersect_key', $args);



回答2:


call_user_func_array('foo', array('foo', 'bar', 'foo N'));

function foo($param1, $param2, $paramN) {
    // TADÁÁÁ
}



回答3:


Take a look into the func_get_args() method for handling this; something like:

function my_function() {
    $numArgs=func_num_args();
    if($numArgs>0) {
        $argList=func_get_args();
        for($i=0;$i<$numArgs;$i++) {
            // Do stuff with the argument here
            $currentArg=$argList[$i];
        }
    }
}



回答4:


function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />";
    $arg_list = func_get_args();
    foreach($arg_list  as $arg) {
        if(is_array($arg)) print_r($arg)."<br />";  
        else echo "<br />".$arg;
    }
}

foo(array(1,2,3), 2, 3);



回答5:


Please refer the http://php.net site first before asking about the standard functions, because you get all your questions answered there itself.

http://php.net/manual/en/function.array-intersect-key.php

http://php.net/manual/en/function.func-get-args.php

http://php.net/manual/en/ref.funchand.php

I got your question, here is one way you can do that :

$arr_of_arr = array($arr1, $arr2, $arr3, ..., $arrn);

or

$arr_of_arr = func_get_args();

if(count($arr_of_arr) > 1){
    for($i = 0; $i < count($arr_of_arr) - 1; $i++){
        if(! $i){
            $intersec = array_intersect_key($arr_of_arr[0], $arr_of_arr[1]);
            $i = 2;
        }
        else{
            $intersec = array_intersect_key($intersec, $arr_of_arr[$i++]);
        }
    }
}

$intersec would now contain the intersection.




回答6:


The array_intersect_keyhas already a protoype allowing multiple inputs :

array array_intersect_key ( array $array1 , array $array2 [, array $ ... ] )

So I don't really see the issue there.



来源:https://stackoverflow.com/questions/10128477/call-function-with-unknown-variable-number-of-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!