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 Answers 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the first way is what I want.
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.

Comments

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

Comments

0

Use this:

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

And the you can invoke:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.