Home >Backend Development >PHP Problem >PHP finds the sum of elements of a one-dimensional array
php is a very popular programming language with many practical functions. In PHP, finding the sum of one-dimensional array elements is a very basic operation. Let’s introduce it in detail below.
In PHP, finding the sum of elements of a one-dimensional array can be achieved by looping through the array. The specific operation method is as follows:
1. Define an array
First, we need to define a one-dimensional array, which can be achieved through the following code:
$arr = array (1, 2, 3, 4, 5);
Here we define an array containing 5 elements, each element has a value of 1, 2, 3, 4, 5 respectively.
2. Use a loop to traverse the array
Next, we need to use a loop to traverse the array to calculate the sum of the elements. Usually, you can use a for loop or a foreach loop to implement the traversal operation. Here we take the foreach loop as an example. The code is as follows:
$sum = 0; // Define a variable to store the sum of elements
foreach ($arr as $value) {
$sum += $value; // 每次遍历将元素值加上
}
In the above code, we define a variable $sum to store the sum of elements. Then use a foreach loop to iterate through the array and add the value of each element to finally get the sum of the elements.
3. Output the calculation results
Finally, we need to output the calculation results, the code is as follows:
echo "The sum of the array elements is: $sum";
The echo statement is used here to output the calculation results to the screen.
The complete code is as follows:
$arr = array(1, 2, 3, 4, 5); // Define an array
$sum = 0; // Define a variable Used to store the sum of elements
foreach ($arr as $value) {
$sum += $value; // 每次遍历将元素值加上
}
echo "The sum of the array elements is: $sum"; // Output the calculation result
Through the above code, we can easily find the sum of the elements of a one-dimensional array.
In addition to using the loop traversal method, you can also use the PHP built-in function array_sum() to calculate the sum of one-dimensional array elements. The specific method is as follows:
$arr = array(1, 2, 3, 4, 5); // Define an array
$sum = array_sum($arr); // Use the array_sum() function Calculate the sum of elements
echo "The sum of the array elements is: $sum"; // Output the calculation result
In the above code, we use the array_sum() function to calculate the sum of the elements, and then The results are output to the screen.
Summary:
Finding the sum of one-dimensional array elements is a very basic operation in PHP, which can be achieved using the loop traversal method or the built-in function array_sum(). If developers are not skilled in operating array elements, they can refer to the above method.
The above is the detailed content of PHP finds the sum of elements of a one-dimensional array. For more information, please follow other related articles on the PHP Chinese website!