Home > Backend Development > PHP Problem > How to find the sum of an array in php

How to find the sum of an array in php

小老鼠
Release: 2023-06-05 15:29:41
Original
1323 people have browsed it

php method to find the sum of an array: 1. Define a variable assigned the value "0" to store the summation result. The code is "$sum=0;"; 2. Use the "foreach" statement to loop through Array, the syntax is "foreach ($array as $value){loop statement block}"; 3. In the loop body, use the "if(is_numeric()){...}" syntax to detect whether the array element is a number, and Add the numerical elements and sum them; 4. Output the result through echo.

How to find the sum of an array in php

The operating environment of this tutorial: Windows 10 system, PHP version 8.1.3, DELL G3 computer.

php seeks array Sum method

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

Traverse the given $array array and assign the value of the current array to $value in each loop.

Step 3: In the loop body, use is_numeric() to detect whether the array elements are numbers (or numeric strings), and add and sum the numeric elements

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

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

How to find the sum of an array in php

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