Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have associative array (dynamic-may have more arrays but same keys):

  Array
 (
  [food] => Array
    (
        [0] => 3
        [1] => 4
        [2] => 1
    )

[liquor] => Array
    (
        [0] => 4
        [1] => 5
        [2] => 0
    )

[beer] => Array
    (
        [0] => 5
        [1] => 6
        [2] => 0
    )

)

I need to use array_sum on each array so result would be:

Array ( [food] => 8, [liquor] => 9, [beer] => 11 )

Thanks!

share|improve this question

1 Answer

up vote 5 down vote accepted
$result = array_map('array_sum', $your_array);

Example: http://ideone.com/LqTAV

share|improve this answer
array_sum needs to be quoted, don't rely on an undefined constant mapping to a string (+1 for the right idea though). – alex Sep 29 '11 at 23:48
I get error too: Notice: Use of undefined constant array_sum - assumed 'array_sum' But array_map - good to know. – phpJs Sep 29 '11 at 23:52
@hakre - I preferred to just fix it to be quoted after alex's expanded comment; kindly stop futzing with the answer. >.< – Amber Sep 29 '11 at 23:52
us.php.net/array_map - function signature has a $callback as the first parameter. See us.php.net/manual/en/… -- "A PHP function is passed by its name as a string." In most environments, leaving it unquoted won't be a problem, but for maximum compatibility, quoting is correct. – artlung Sep 29 '11 at 23:58
@artlung: I'd argue it's never a good idea to pass it unquoted. – alex Sep 30 '11 at 0:01
show 2 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.