How to use php array_sum() function?

How to use php array_sum() function?

Posted on:July 22, 2019 at 10:00 AM

In PHP, there is a built-in function called array_sum(). Normally array_sum() help to sum all the elements in an array. Today, I will show you the purpose of array_sum() and a practical uses of it.

Consider the following code, that helps you to sum all the elements of an array.

<?php

$arrayValues = [2,5,3];

$result = 0;

foreach($arrayValues as $value){
	$result += $value;
}

echo $result;

The above code normally slices all the element of the array and then sum-up the value. This code should return 10.

The code works fine, but I am not happy to write a few lines of code to sum-up elements of an array only. Don’t you think it’s expensive?

Well, here what I come up with array_sum().

<?php

$arrayValues = [2,5,3];

echo array_sum($arrayValues);

Normally both of them work same and we get the same output. Don’t you think array_sum() is better in this case?