In PHP programming, arrays are an important data type. Arrays can be used to conveniently store a series of related data. When you need to perform numerical calculations on the elements in an array, PHP provides a function array_sum() that can sum the array.
The array_sum() function accepts an array as a parameter and returns the sum of all elements in the array. The following is a sample code:
$numbers = array(1, 2, 3, 4, 5); $total = array_sum($numbers); echo "数组中所有元素的总和为:$total";
In the above code, an array $numbers is first defined, containing 5 integers. Then call the array_sum() function, passing the array $numbers as a parameter to the function. The function returns the sum of all elements in the array and stores the result in the variable $total. Finally, use the echo statement to output the sum.
In addition to integers, the array_sum() function also supports summing arrays of floating point numbers, strings and other types. The following is a sample code:
$prices = array(1.1, 2.2, 3.3, 4.4, 5.5); $total = array_sum($prices); echo "所有价格的总和为:$total";
In the above code, an array $prices is first defined, containing 5 floating point numbers. Then call the array_sum() function, passing the array $prices as a parameter to the function. The function returns the sum of all elements in the array and stores the result in the variable $total. Finally, use the echo statement to output the sum.
It should be noted that if the array contains non-numeric elements, the array_sum() function will treat them as 0. The following is a sample code:
$items = array('apple', 'banana', 'orange', 2.2, 3.3); $total = array_sum($items); echo "所有物品的总和为:$total";
In the above code, an array $items is first defined, containing 5 elements, including 3 strings and 2 floating point numbers. Then call the array_sum() function, passing the array $items as a parameter to the function. Since the array contains non-numeric elements, the function treats them as 0. Therefore, the function returns a value of 5.5 and stores the result in the variable $total. Finally, use the echo statement to output the sum.
In general, the array_sum() function is a very useful function in PHP, which can easily sum arrays. When using this function, you need to pay attention to the type of elements in the array to ensure correct calculation results.
The above is the detailed content of How to sum an array in php. For more information, please follow other related articles on the PHP Chinese website!