Master PHP’s array_sum(): Quick Guide to Summing Arrays Efficiently

This article explains PHP’s built‑in array_sum() function, covering its syntax, parameters, return values, handling of empty or non‑numeric arrays, and provides clear code examples to help developers sum array elements correctly.

php Courses
php Courses
php Courses
Master PHP’s array_sum(): Quick Guide to Summing Arrays Efficiently

Syntax

array_sum(array $array): number

Parameter Description

$array

: The array whose elements are to be summed; it must be a numeric array.

Return Value

The function returns the sum of all numeric elements in the array. If the array is empty, it returns 0. Non‑numeric elements are ignored.

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 above script defines a numeric array $numbers, calls array_sum(), and prints Array sum is: 15.

Handling Empty Arrays

If $array contains no elements, array_sum() returns 0 because there are no values to add.

Ignoring Non‑Numeric Elements

When the array includes strings, booleans, or other non‑numeric types, those entries are skipped during the calculation.

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

$sum = array_sum($numbers);

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

In this case, the string "3" and the boolean true are ignored, so the function returns 7, and the output is Array sum is: 7.

Conclusion

The array_sum() function is a convenient tool for quickly summing numeric arrays in PHP. It works with both integers and floats, returns 0 for empty arrays, and safely ignores any non‑numeric elements, helping developers avoid calculation errors.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPphp-functionsarray sumphp-tutorialarray_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

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.