Adding up digits

A

Anonymous

Guest
I'm stuck on what appears to be a trivial bit of scripting and would appreciate a push in the right direction!

Suppose I have a number written like $total = "0-1234 567*89".

I want to SUM the total of the individual digits while ignoring any non-numeric characters.

Like this: 0+1+2+3+4+5+6+7+8+9

Suggestions please?

Martin

Code:
$total = "0-1234 567*89";
echo ((float)$total);
0
Hmm

Code:
$total = "0123456789";
echo ((float)$total);
123456789
 
OK, I'm getting there:

Code:
$total = "0-1234 567*89"
$string = substr(chunk_split($total, 1, ':'), 0, -1); 
$pieces = explode (":", $string);

Now I just have to SUM the numbers in the array.
 
Code:
<?
$total = "0-1234 567*89";
$string = substr(chunk_split($total, 1, ':'), 0, -1); 
$pieces = explode (":", $string);
echo (array_sum($pieces));
?>

Well, I said it was trivial! :D
 
Back
Top