Home >Database >Mysql Tutorial >How to Sum Column Values in a Multidimensional Array Without Loops in PHP?
Sum Column Values in a Multidimensional Array Without Loops
When working with multidimensional arrays, calculating the sum of specific column values can be challenging. Consider the following array:
Array ( [0] => Array ( [f_count] => 1 [uid] => 105 ) [1] => Array ( [f_count] => 0 [uid] => 106 ) [2] => Array ( [f_count] => 2 [uid] => 107 ) [3] => Array ( [f_count] => 0 [uid] => 108 ) [4] => Array ( [f_count] => 1 [uid] => 109 ) [5] => Array ( [f_count] => 0 [uid] => 110 ) [6] => Array ( [f_count] => 3 [uid] => 111 ) )
The desired output is the sum of the f_count values, which is 7.
Solution Without Loops
For PHP versions 5.5 and above, a concise solution is available using the array_column and array_sum functions:
$f_counts = array_column($array, 'f_count'); $sum = array_sum($f_counts);
This approach avoids the need for loops or complex data manipulation techniques.
Alternative Solution
If using a different version of PHP, or if you prefer, you can achieve column value summation using a more traditional approach:
$sum = 0; foreach ($array as $row) { $sum += $row['f_count']; }
The above is the detailed content of How to Sum Column Values in a Multidimensional Array Without Loops in PHP?. For more information, please follow other related articles on the PHP Chinese website!