Home >Backend Development >PHP Tutorial >How Can I Efficiently Sum the Values in a 2D Array's Column in PHP?

How Can I Efficiently Sum the Values in a 2D Array's Column in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 05:08:14674browse

How Can I Efficiently Sum the Values in a 2D Array's Column in PHP?

Summing Values in a 2D Array's Column Efficiently

Consider an array of user data with "f_count" and "uid" fields. To sum values in the "f_count" column without using a foreach loop, the following techniques offer effective solutions:

In PHP versions 5.5 , utilize the array_column() and array_sum() functions, which provide an elegant solution:

$value = array_sum(array_column($arr, 'f_count'));

Another efficient approach for PHP 5.4 and above employs array_reduce() in conjunction with an anonymous function:

$value = array_reduce($arr, function ($carry, $item) {
    return $carry + $item['f_count'];
}, 0);

Both techniques avoid iterative loops, resulting in improved performance.

Alternatively, modifying the database query to return a flattened array can also eliminate the need for further processing:

$query = "SELECT SUM(f_count) AS total_f_count FROM users WHERE gid=:gid";

This query will return a single row containing the sum of f_counts, rendering subsequent array manipulation unnecessary.

The above is the detailed content of How Can I Efficiently Sum the Values in a 2D Array's Column in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn