2
0 => array(
    'key1' = value
    'key2' = value
    }
1 => array(
    'key1' = value
    'key2' = value
    }

Is there a fast way of getting the sum of id=>key1 and id2=key1 so that I don't have to loop through?

I'd like it to see the array as

array(
    0 = value (key1)
    1 = value (key1)
)

But if it isn't built in somehow, it probably would be another step.

9
  • 1
    Unless you're dealing with huge arrays I doubt the impact of looping will be too big to manage. Don't worry about performance until you have a performance problem. First and foremost of things your programs should be is correct. Commented Jun 8, 2014 at 22:27
  • It wouldn't be such a bad feature though, would it? to quickly index multidimensional arrays by a contained key value if asked for. It seems like something people would want to do. Maybe my data model isn't great if it requires loops like this. Commented Jun 8, 2014 at 22:31
  • thanks GordonM. :) well said. The arrays can be very big and some of the bigger ones are taking .08 seconds - and I might need to do 20 or more at a time for a web facing application. I'd like to keep the render time at least under half a second but I don't think anyone will complain if it takes a second. Commented Jun 8, 2014 at 22:34
  • it would require a 'loop' even if it was an internal function, you seem to be seeking magic Commented Jun 8, 2014 at 22:34
  • Dagon, that is funny. I thought that some internal functions were handled natively and therefore offer a difference in performance. Commented Jun 8, 2014 at 22:37

1 Answer 1

1

Using PHP 5.5's array_column() function

$result = array_sum(
    array_column(
        $myArray,
        'key1'
    )
);

for PHP < 5.5

$result = array_sum(
    array_map(
        $myArray,
        function ($value) { return $value['key1']; }
    )
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I don't have php 5.5 and had read about array_map, but hadn't figured out how to use it. All of the different options reduce/walk/etc had been a bit confusing.
and they still all uses loops :-)

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.