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
<?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

Similar Reads

Using array_sum() Function

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....

Using for Loop

We can use for loop to calculate the sum of array elements. First, we declare a variable and initialize with zero and then loop over array elements and sum up each array element in the declared variable....

Using array_reduce() Function

The array_reduce() function is used to reduce the array elements into a single value that can be of float, integer or string. The function uses a user-defined callback function to reduce the input array....

Using Recursion

We can use recursion to calculate the sum of array values. The recursive calculates the sum of an array by breaking it down into two cases: the base case, where if the array is empty the sum is 0; and the recursive case, where the sum is calculated by adding the first element to the sum of the remaining elements which is computed through a recursive call with the array shifted by one position and size reduced by one....

Using foreach Loop

To calculate the sum of array elements in PHP using a `foreach` loop, initialize a sum variable to 0, then iterate through each element of the array, adding its value to the sum. Finally, echo or return the sum....