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?
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?
multiple options, here is 1.
$start=1;
$end=5;
$sum=0;
for ($i = $start; $i <= $end; $i++) {
$sum+=$i;
}
echo $sum;
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;
?>
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));
?>