Skip to content

Instantly share code, notes, and snippets.

@neilh-cogapp
Created October 16, 2018 10:07
Show Gist options
  • Save neilh-cogapp/9fe162b065f2d7907d7a9f59e49fe5d0 to your computer and use it in GitHub Desktop.
Save neilh-cogapp/9fe162b065f2d7907d7a9f59e49fe5d0 to your computer and use it in GitHub Desktop.
Calculate sum of a particular column within a multi-dimensional php array.
<?php
/**
* Calculates the sum for a particular column in a multidimensional array.
*
* @param array $array
* Input array.
* @param string $key
* The key for which sum should be calculated.
*/
protected function sumArrayColumn(array $array, string $key) {
return array_reduce($array, function ($reduced, $item) use ($key) {
$reduced += (int) $item[$key];
return $reduced;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment