1

How can I sum of all numbers within a number range using PHP?

For example:

1-5 (1+2+3+4+5) = 15

Do I need to use array_sum or a variation of array?

Billu
  • 2,733
  • 26
  • 47

3 Answers3

1

Yeah use array_sum() and range().

echo array_sum(range(1,5)); //"prints" 15

Demonstration

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • certainly more elegant than my option, but a little slower according to my benchmarking ;-) –  Apr 24 '14 at 03:54
1

multiple options, here is 1.

$start=1;
$end=5;
$sum=0;
for ($i = $start; $i <= $end; $i++) {
$sum+=$i;
}

echo $sum;
-1

Solution 1: Manually using loop

<?php
$startNum = 1;
$endNum = 5;
$sum = 0;
for($i = $startNum; $i <= $endNum; $i++){
  $sum = $sum + $i;
}
echo "Sum of given range is ".$sum;
?> 

Check code with result enter image description here


Solution 2: Using built-in functions

Function range() is used to take given range and function array_sum() used to calculate sum of given range/array.

<?php
    echo "Sum of given range is ".array_sum(range(1,5));
?> 

Check code with result enter image description here

Billu
  • 2,733
  • 26
  • 47
  • see: [Warning: Undefined variable $sum](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-warning-undefined-arr) – Luuk Oct 02 '22 at 09:24
  • @Luuk answer updated. Actually the main thing is the logic. – Billu Oct 02 '22 at 16:10