Home  >  Article  >  Backend Development  >  Find the sum of one-dimensional arrays using php

Find the sum of one-dimensional arrays using php

WBOY
WBOYOriginal
2023-05-19 18:53:08722browse

In PHP, we can use the array_sum() function to calculate the sum of a one-dimensional array. This function adds all the values ​​in the array and returns their sum.

The following is a sample code that uses the array_sum() function to calculate the sum of a one-dimensional array:

// 创建一个一维数组
$array = array(1, 2, 3, 4, 5);

// 计算数组的总和
$sum = array_sum($array);

echo "数组的总和是:" . $sum;

The output result is:

数组的总和是:15

In addition to using the array_sum() function, we also You can use a for loop or foreach loop to iterate through an array and calculate the sum. The following is a sample code that uses a for loop to calculate the sum of a one-dimensional array:

// 创建一个一维数组
$array = array(1, 2, 3, 4, 5);

// 初始化总和为0
$sum = 0;

// 使用for循环遍历数组并计算总和
for($i = 0; $i < count($array); $i++){
    $sum += $array[$i];
}

echo "数组的总和是:" . $sum;

The output result is:

数组的总和是:15

The foreach loop can also be used to calculate the sum of a one-dimensional array. The following is a sample code:

// 创建一个一维数组
$array = array(1, 2, 3, 4, 5);

// 初始化总和为0
$sum = 0;

// 使用foreach循环遍历数组并计算总和
foreach($array as $value){
    $sum += $value;
}

echo "数组的总和是:" . $sum;

The output result is:

数组的总和是:15

In summary, using the array_sum() function is the simplest and fastest way to calculate the sum of a one-dimensional array, but using a for loop or foreach loop is also A possible approach. Developers can choose the appropriate method according to their actual situation and preferences.

The above is the detailed content of Find the sum of one-dimensional arrays using 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