-1

I want to calculate all input values in text which are having or not having trailing commas.
Example I input 2,3,4,5 or 2345 in text box. Its sum should come as 14, provided user has used or not used , in between numbers.

Til
  • 5,150
  • 13
  • 26
  • 34

3 Answers3

0
function calculateStringNumbers($string)
{
    $sum = 0;
    $numbers_array = explode(',',$string);

    if(is_array($numbers_array) && count($numbers_array) > 0 && strpos($string, ',') !== false)
    {
        $sum = array_sum($numbers_array);
    }
    else
    {
        $sum = sum($string);
    }

    echo 'Your Sum is: '.$sum.' cheers';
}


function sum($num) {
    $sum = 0;
    for ($i = 0; $i < strlen($num); $i++){
        $sum += $num[$i];
    }
    return $sum;
}

Test Cases:

1 - user input 2345: calculateStringNumbers('2345') Output Your Sum is: 14 cheers

2 - user input 2,3,4,5: calculateStringNumbers('2,3,4,5') Output Your Sum is: 14 cheers

0

My more concise solution would be:

$sum = array_sum(preg_split('/[\s,]*/', $input));
Joe
  • 877
  • 1
  • 11
  • 26
-1

Lucking after posting my questions , i manage to find a solution by myself.. here it is:

<form method="POST" action="">
<input type="text" name="checkname"/>
<input type="submit" name="mysubmit"/>
</form>
<?php
if (isset($_POST['mysubmit']))
{
$test=$_POST['checkname'];

$search_comma=strpos($test,',');    

$testexp=explode(',',$test);

$allsum=implode('',$testexp);

$allsum=preg_replace('/\s+/', '', $allsum);

$sum=0;

for($i=0;$i<strlen($allsum);$i++)
{
 $sum=$sum+$allsum[$i];
}
 echo 'Your Sum is:'.$sum;
}

User Input 1:1,2,3,4

User Input 2:1234

=================

Output: Your Sum is:10 cheers :)