mika
mika

Reputation: 33

A total sum of sequential numbers in PHP

This is a simple question,I guess, but I couldn't figure it out.

How do I get a total sum of sequential numbers in PHP Like 2,4,6,8,10 . . . .1000

Thank you for the help.

Upvotes: 3

Views: 2015

Answers (3)

Scott Chamberlain
Scott Chamberlain

Reputation: 127593

If you wanted to you could also use the Arithmetic progression sum and just do

$total = ($firstNumber + $lastNumber) * $count / 2

This will work as long as the numbers are a expressable in the format

an = a1 + (n - 1)d

Your sequence could be described as

an = 2 + (n - 1)2

So we can apply the Arithmetic progression sum and get

(2 + 1000) * 500 / 2 = 250,500

This will be much much faster than any array_sum method of calculating it.

Upvotes: 3

Rob
Rob

Reputation: 12872

$sum = array_sum(explode(',', '2,4,6,8'));

edit: if you just want the sum of even numbers within a range you could

$sum = array_sum(range(2,1000,2));

Upvotes: 4

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

Split on , and then sum:

$numbers = explode(",", $string);
$total = array_sum($numbers);
echo $total;

Note that this requires only numbers and , any other characters will be subject of being typecasted to an integer (which could result in unexpected results).

Upvotes: 4

Related Questions