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

How to sum arrays in PHP based on specified conditions

青灯夜游
Release: 2023-03-16 10:48:02
Original
3628 people have browsed it

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;
Copy after login

Step 2: Use the foreach statement to loop through the array

foreach ($arr as $v){
    //循环体语句块;
}
Copy after login

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;
}
Copy after login

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

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = [1,2,3,4,5,6,7,8,9,10];
var_dump($arr);
$sum=0;
foreach($arr as $v){
	if($v%2==0){
		$sum+=$v;
	}
}
echo "数组偶数和为:".$sum;
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template