PHP Array Sum Example | PHP array_sum() Function Tutorial

Like Tweet Pin it Share Share Email
PHP Array Sum Example | PHP array_sum() Function Tutorial

PHP Array Sum Example | PHP array_sum() Function Tutorial is today’s topic. It returns the sum of all the values in the array. It takes an array parameter and returns the sum of all the values in it. It returns the 0 if the array is empty. The returned sum may be integer or float.

PHP Array Sum Example

It calculates a sum of values in an array.

See the following syntax.

array_sum($array)

Now, see the following code example.

<?php

// app.php

$arr = [19, 21, 46];
echo array_sum($arr);

See the following output.

PHP Array Sum Example

If you want to find an AVERAGE of the values in your array, use the sum and count the functions together.  For example, let’s say your array is $arr and you want the average.

<?php

// app.php

$arr = [19, 21, 46];
$average = array_sum($arr) / count($arr);
echo $average;

See the below output.

PHP array_sum() Function Tutorial

So, we can calculate the sum of values in an array using array_sum() function.

Empty Array

Let’s see the example where the array is empty.

<?php

// app.php

$arr = [];
echo array_sum($arr);

See the output.

Empty Array

Integers and String Values in array_sum()

If you pass the array containing both the strings and integers. Then the PHP array_sum() Function returns a sum of integers. The strings are considered as 0.

<?php

// app.php

$arr = ['krunal', 21, 'ankit', 19];
echo array_sum($arr);

See the following output.

Integers and String Values in array_sum()

If you want to check if there are for example only strings in the array, you can use the combination of array_sum and array_map() as the following code.

<?php

// app.php

function check_only_strings_in_array($arr) {
  return array_sum(array_map('is_string', $arr)) == count($arr);
}
$arr1 = array('1', 2);
$arr2 = array(1, 2, []);
$arr3 = array('krunal', 'ankit');

var_dump(
  check_only_strings_in_array($arr1),
  check_only_strings_in_array($arr2),
  check_only_strings_in_array($arr3)
);
?>
See the following output.
array_map and array_sum

Finally,  PHP Array Sum Example | PHP array_sum() Function Tutorial is over.

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *