Home >Backend Development >PHP Problem >How to find the sum between array elements in php
In PHP, finding the sum between elements of an array is a common operation. There are many ways to achieve this goal. Here are some common methods.
First of all, the most common method is to loop and accumulate array elements. The specific implementation method is as follows:
$myArray = array(1, 2, 3, 4, 5); $sum = 0; for ($i = 0; $i < count($myArray); $i++) { $sum += $myArray[$i]; } echo "数组元素之和为:" . $sum;
This method is very simple , traverse the array elements through a for loop, accumulate each element into the $sum variable, and finally obtain the sum of the array elements.
PHP provides a built-in function array_sum to calculate the sum of array elements. It is very convenient. You only need to pass an array as a parameter, for example :
$myArray = array(1, 2, 3, 4, 5); $sum = array_sum($myArray); echo "数组元素之和为:" . $sum;
array_reduce is another PHP function that is used to calculate all the values in an array according to a specific callback function to obtain a single value. The syntax is as follows:
array_reduce ( array $input , callable $function [, mixed $initial = NULL ] ) : mixed
Among them, $input represents the array that needs to be calculated, $function represents the callback function, and $initial is an optional parameter, indicating the initial value used for calculation.
The following is an example:
$myArray = array(1, 2, 3, 4, 5); $sum = array_reduce($myArray, function($carry, $item) { return $carry + $item; }); echo "数组元素之和为:" . $sum;
This method uses the array_reduce function and an anonymous function. The $carry and $item parameters in the anonymous function represent the calculation result and the current array element respectively. During each iteration, the current element is added to $carry, and the sum of the array elements is finally obtained.
The eval function can execute a string as PHP code. If you convert the array to a string and put it in the eval function, you can get The sum of array elements. For example:
$myArray = array(1, 2, 3, 4, 5); $sum = eval('return ' . join('+', $myArray) . ';'); echo "数组元素之和为:" . $sum;
This method splices the array elements into an addition expression, and passes it to the eval function for execution, and finally gets the sum of the array elements.
Summary
The above are four methods for calculating the sum of array elements. Among them, array_sum and array_reduce functions are built-in in PHP and are more efficient. Although the eval function is simple, it may be safe. question and need to be used with caution. No matter which method you choose, you should choose the most appropriate method based on your specific application scenario.
The above is the detailed content of How to find the sum between array elements in php. For more information, please follow other related articles on the PHP Chinese website!