Home>Article>Backend Development> How to sum arrays in PHP based on specified conditions
Method: 1. Use "$sum=0;" to define a variable to store the summation result; 2. Use "foreach($arr as $v){}" to loop through the array; 3. In the loop body , use the if statement to set the conditional filter elements, and add the elements that meet the condition to sum. The syntax is "if (condition) {$sum =$v;}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
The PHP array is specified according to Conditional summation
#Step 1: Define a variable assigned a value of 0 to store the summation result.
$sum=0;
Step 2: Use the foreach statement to loop through the array
foreach ($arr as $v){ //循环体语句块; }
Traverse the given $arr array, and in each loop, the current array will be The value is assigned to $v.
Step 3: In the loop body, use the if statement to set the conditional filter elements, and add and sum the elements that meet the conditions
if(条件){ $sum+=$v; }
After the loop ends, $sum The value is the summation result.
Example: Add and sum even elements
Even elements are values divisible by 2, see using$v%2==0
Conditions to judge
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to sum arrays in PHP based on specified conditions. For more information, please follow other related articles on the PHP Chinese website!