OneBite.Dev - Coding blog in a bite size

Find The Sum Of All Elements In An Array In PHP

Code snippet for how to Find The Sum Of All Elements In An Array In PHP with sample and detail explanation

Managing and manipulating arrays is a common task in PHP. In this article, we will discuss a straightforward and effective method to compute the sum of all elements in an array using PHP.

Code snippet for Array SUM

<?php
$numbers = array(2, 3, 4, 5, 6);
echo array_sum($numbers);
?>

Code Explanation for Array SUM

The PHP script presented in the code snippet makes use of PHP’s inbuilt function array_sum(). This function calculates the sum of all numerical values in an array.

Step by step, here’s how it works:

  1. We first declare a variable $numbers, which holds an array of numeric values - in this case 2, 3, 4, 5, 6.
$numbers = array(2, 3, 4, 5, 6);
  1. Next, we leverage the array_sum() function by passing the $numbers variable to it. The array_sum() function iterates through each value in the array, adding them together.
echo array_sum($numbers);
  1. After the array_sum() function has summed all the elements in the array, the total is returned, and in this case, it is output to the browser using the echo statement.

The result of the above code snippet would be the integer 20 - because 2, 3, 4, 5, and 6 add up to 20.

To sum up, the array_sum() function is simple and useful for quickly calculating the sum of all elements in an array in PHP. Its ease of use and efficiency make it a valuable tool for any PHP programmer.

php