Blueberry Hill
Blueberry Hill

Reputation: 119

Call function with (unknown) variable number of parameters?

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);

Upvotes: 4

Views: 5349

Answers (6)

vedarthk
vedarthk

Reputation: 1333

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.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146201

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);

Upvotes: 0

Cal
Cal

Reputation: 7157

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);

Upvotes: 7

faino
faino

Reputation: 3224

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];
        }
    }
}

Upvotes: 0

Gabriel Santos
Gabriel Santos

Reputation: 4974

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

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

Upvotes: 0

Claaker
Claaker

Reputation: 257

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.

Upvotes: -1

Related Questions