Current Location: Home> Latest Articles> How to Use array_sum with array_filter to Implement Conditional Summation Techniques?

How to Use array_sum with array_filter to Implement Conditional Summation Techniques?

gitbox 2025-08-25

<?php
// Main content begins
echo "

How to Use array_sum with array_filter to Implement Conditional Summation Techniques?

";

echo "

In PHP development, it’s common to sum the elements of an array, but this often requires meeting certain conditions. PHP provides two very useful functions: array_filter and array_sum. Used together, they allow efficient conditional summation.

"
;

echo "

1. Introduction to array_filter

"
;
echo "

The array_filter function filters array elements based on a callback function. The syntax is as follows:

"
;
echo "
array array_filter(array $array, callable $callback)
"
;
echo "

Here, elements for which the callback returns true are kept, while those returning false are removed.

"
;

echo "

2. Introduction to array_sum

"
;
echo "

The array_sum function calculates the sum of all values in an array. The syntax is:

"
;
echo "
mixed array_sum(array $array)
"
;
echo "

It returns the total of all numeric elements in the array.

"
;

echo "

3. Example: Conditional Summation

"
;
echo "

Suppose we have an array and want to sum only the elements greater than 10:

"
;

echo "

<br>
$numbers = [5, 12, 8, 20, 7];</p>
<p>// Use array_filter to keep elements greater than 10<br>
$filtered = array_filter($numbers, function($value) {<br>
return $value > 10;<br>
});</p>
<p>// Use array_sum to calculate the sum<br>
$sum = array_sum($filtered);</p>
<p>echo $sum; // Output 32<br>
"
;

echo "

In this example, array_filter first extracts elements greater than 10 [12, 20], then array_sum sums them up to get 32.

";

echo "

4. Advanced Usage: Complex Conditions

"
;
echo "

If the filtering condition is more complex, for example summing only even numbers greater than 5, you can write:

"
;

echo "

<br>
$numbers = [2, 4, 6, 8, 10, 3, 7];</p>
<p>// array_filter with multiple conditions<br>
$filtered = array_filter($numbers, function($value) {<br>
return $value % 2 === 0 && $value > 5;<br>
});</p>
<p>// Sum them<br>
$sum = array_sum($filtered);</p>
<p>echo $sum; // Output 24 (6+8+10)<br>
"
;

echo "

This way, you can easily perform multi-condition array summation without manually looping and checking.

";

echo "

5. Summary

"
;
echo "

By combining array_filter and array_sum, you can achieve flexible and efficient conditional summation. The key idea is to first use array_filter to extract elements that meet the condition, and then apply array_sum to calculate the total. This results in clean, maintainable code.

"
;
?>