PHP Tutorial PHP Advanced PHP Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

PHP - Array array_sum() Function



The PHP Array array_sum() function returns the sum of all values in the array. Please note that, the function converts string elements of the array into numbers. If a element can not be converted into number, it is converted to 0.

Syntax

array_sum(array)

Parameters

array Required. Specify an array.

Return Value

Returns the sum of all values in the array.

Exceptions

NA.

Example:

In the example below, array_sum() function is used to calculate the sum of all values in the given indexed array.

<?php
$MyArray = array(1, 2, 3, 4, 5);
$sum = array_sum($MyArray);

echo $sum;
?>

The output of the above code will be:

15

Example:

In the example below, the function is used to calculate the sum of all values in the given associative array.

<?php
$MyArray = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22, "Adam"=>35);
$sum = array_sum($MyArray);

echo $sum;
?>

The output of the above code will be:

157

❮ PHP Array functions

5