Home  >  Article  >  Backend Development  >  How to find the sum of numbers in an array in php

How to find the sum of numbers in an array in php

青灯夜游
青灯夜游Original
2022-06-28 20:30:313433browse

Implementation steps: 1. Define a variable assigned a value of 0 to store the summation result, the syntax "$sum=0;"; 2. Use the foreach statement to loop through the array, the syntax "foreach($array as $ value){loop body statement block}"; 3. In the loop body, use is_numeric() to detect whether the array elements are numbers (or numeric strings), add the numeric elements and sum them, the syntax "if(is_numeric($value )){$sum =$value;}".

How to find the sum of numbers in an array in php

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

php seeks the array Method of summing numbers

#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 ($array as $value){
    循环语句块
}

Traverse the given $array array, and change the value of the current array in each loop Assign to $value.

Step 3: In the loop body, use is_numeric() to detect whether the array element is a number (or numeric string), and add the numeric elements to the sum

if(is_numeric($value)){
$sum+=$value;
}

After the loop ends, the value of $sum is the summation result.

Implementation code:

<?php
header("Content-type:text/html;charset=utf-8");
$array = array("php",1,2,&#39;3&#39;,4,"hello","5",null,true,"6",7,8,"9","a"); 
var_dump($array);
$sum=0;
foreach($array as $value){
	if(is_numeric($value)){
		$sum+=$value;
	}
}
echo "数组中数字的总和:".$sum;
?>

How to find the sum of numbers in an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to find the sum of numbers in an array 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