Sum keyed elements of an array


/ Published in: PHP
Save to your folder(s)

Sum all elements of a bidimensional or multi-dimensional array with an assigned key


Copy this code and paste it in your HTML
  1. /**
  2.  * sum values in array
  3.  *
  4.  * @param array $arr
  5.  * @param string [optional]$index
  6.  * @return int result
  7.  */
  8. function array_sum_key( $arr, $index = null ){
  9. if(!is_array( $arr ) || sizeof( $arr ) < 1){
  10. return 0;
  11. }
  12. $ret = 0;
  13. foreach( $arr as $id => $data ){
  14. if( isset( $index ) ){
  15. $ret += (isset( $data[$index] )) ? $data[$index] : 0;
  16. }else{
  17. $ret += $data;
  18. }
  19. }
  20. return $ret;
  21. }
  22.  
  23. //## To sum elements on a multidimensional finding defined key = 'pv' array
  24.  
  25. $sum = 0;
  26. $array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
  27. foreach($array_obj as $key => $value) {
  28. if($key == 'pv')
  29. $sum += $value;
  30. }
  31. echo $sum;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.