0

In short, I have a function like the following:

function plus($x, $y){
   echo $x+$y;
}

I want to tell the function its parameters as array like the following:

$parms = array(20,10);
plus($parms);

But unfortunately, not work. I'm tired by using another way as the following:

$parms = array(20,10);
$func_params = implode(',', $parms);
plus($func_params);

And also not work, and gives me Error message: Warning: Missing argument 2 for plus(), called in.....

And now, I'm at a puzzled. What can I do to work ?

4

4 に答える 4

1

There is a couple things you can do. Firstly, to maintain your function definition you can use call_user_func_array(). I think this is ugly.

call_user_func_array('plus', $parms);

You can make your function more robust by taking a variable number of params:

function plus(){
  $args = func_get_args();
  return $args[0] + $args[1];
}

You can simply accept an array and add everything up:

function plus($args){
  return $args[0] + $args[1];
}

Or you could sum up all arguments:

function plus($args){
  return array_sum($args);
}

This is PHP, there are 10 ways to do everything.

于 2012-09-19T00:42:27.473 に答える
0

You need to adapt your function so that it only accepts one parameter and then in the function itself, you can process that parameter:

Very simple example:

function plus($arr){
   echo $arr[0]+$arr[1];
}

$parms = array(20,10);
plus($parms);

You can easily adapt that to loop through all elements, check the input, etc.

于 2012-09-19T00:39:42.810 に答える
0

Heh? The error message is very clear: you ask for two parameters in your function, but you only provide one.

If you want to pass an array, it would be a single variable.

function plus($array){
    echo ($array[0]+$array[1]);
}
$test = array(1,5);
plus($test); //echoes 6
于 2012-09-19T00:40:40.157 に答える
0

Use this:

function plus($arr){
   $c = $arr[0]+$arr[1];
   echo $c;
}

And the you can invoke:

$parms = array(20,10);
plus($parms);
于 2012-09-19T00:40:44.657 に答える