Home>Article>Backend Development> How to sum arrays in PHP based on specified conditions

How to sum arrays in PHP based on specified conditions

青灯夜游
青灯夜游 Original
2022-06-02 19:49:03 3414browse

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;}".

How to sum arrays in PHP based on specified conditions

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==0Conditions to judge

How to sum arrays in PHP based on specified conditions

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!

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