Backend Development 4 min read

How to Use PHP's array_sum() Function to Sum Array Elements

This article explains the PHP array_sum() function, covering its syntax, parameter requirements, return values, handling of empty arrays and non‑numeric elements, and provides clear code examples demonstrating how to calculate the sum of numeric arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP's array_sum() Function to Sum Array Elements

In PHP, arrays are a common data structure and developers often need to calculate the sum of all elements. PHP provides the built‑in array_sum() function for this purpose.

The function array_sum() computes the sum of all numeric values in an array and returns the result. It works with both integer and floating‑point arrays; non‑numeric elements are ignored.

Syntax:

array_sum(array $array): number

Parameter Description:

$array : The array whose elements are to be summed. Must be a numeric array.

Return Value:

Returns the sum of the array elements. If the array is empty, the function returns 0 .

Example Code:

<?php
// Example array
$numbers = [1, 2, 3, 4, 5];

// Calculate the sum of all elements
$sum = array_sum($numbers);

// Output the result
echo "Array sum is: $sum";
?>

The code defines a numeric array $numbers , calls array_sum() with it, and prints the sum, which is 15 in this case.

If the array is empty, array_sum() returns 0 because there are no elements to add.

When the array contains non‑numeric values, such as strings or booleans, those elements are ignored during the sum calculation.

Non‑Numeric Elements Example:

<?php
// Example array with non‑numeric values
$numbers = [1, 2, "3", 4, true];

// Calculate the sum
$sum = array_sum($numbers);

echo "Array sum is: $sum";
?>

In this example, the string "3" and the boolean true are ignored, so the function returns 7 (1+2+4).

Overall, array_sum() is a convenient function for summing numeric arrays in PHP, handling both integers and floats, while safely ignoring non‑numeric entries.

BackendPHPsumphp-functionsarray_sum
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.