0

I have a function called array_sum_identical_keys() which adds (as a sum) array values of identical keys. I have X number of arrays called $array1 $array2 $array3 etc. all created from a loop earlier in the code.

Since I have X number of arrays, I need to create a loop which will add up all of the array values with my custom function array_sum_identical_keys(), given that I don't know how many arrays I have.

I need to pass each array as an argument to array_sum_identical_keys() like array_sum_identical_keys($array1, $array2, ...) but I need to do this within a loop, adding each argument every time the loop iterates.

In simpler terms: I need to add an argument to a function each time a loop iterates, but I need the function to just be called once, with all arguments.

What would be the best way to go about doing this?

3
  • I have an answer but post how you create arrays if you need more. Commented Dec 18, 2016 at 5:28
  • strore each array $array1, $array2 etc in an array itself. then pass that array as parameter to your method Commented Dec 18, 2016 at 5:28
  • The reference manual gives some good tips, php.net/manual/en/functions.arguments.php then scroll down to Variable-length argument lists. Commented Dec 18, 2016 at 5:30

2 Answers 2

2

Instead of creating separate arrays, create a multi-dimensional array in the loops that is an array of your arrays. Then just send that to call_user_func_array():

$result = call_user_func_array('your_func', $array);
Sign up to request clarification or add additional context in comments.

Comments

0

If you'd rather not deal with variable length argument lists, and would rather create a solution from simple parts, then this sounds like a perfect use for the array_reduce. If your array_sum_identical_keys works for two input arrays, and you have all of your arrays bundled up into a multidimensional array $arrays, then you can simply put the following:

$arrays_summed = array_reduce($arrays, 'array_sum_identical_keys');

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.