How to use array_sum() Function In PHP
The array_sum() function returns the sum of all the values in an array (one-dimensional and associative). It takes an array parameter and returns the sum of all the values in it.
Syntax
int|float array_sum( array $array );
Example: PHP Program to get the sum of all the Array Elements using the array_sum() Function.
<?php
// Array with values
$arr = [21, 12, 16, 14, 18, 22];
// Calculating sum of array elements
$sumofelements = array_sum($arr);
print_r($sumofelements);
?>
Output
103
How to Calculate the Sum of Array Elements in PHP ?
Given an integer array arr of size n, find the sum of all its elements in PHP.
Example: Consider the below examples:
Input : arr[5] = [ 1, 2, 3, 6, 5 ]
Output : 17
Explanation : 1 + 2 + 3 + 6 + 5 = 17
Input : arr[] = [ 15, 12, 13, 10 ]
Output : 50
There are different methods to calculate the sum of array values:
Table of Content
- Using array_sum() Function
- Using for Loop
- Using array_reduce() Function
- Using Recursion
- Using foreach Loop