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.
Asked
Active
Viewed 185 times
-1

Til
- 5,150
- 13
- 26
- 34

Yogesh Raghav
- 1
- 1
- 5
-
1What if the user wants to input `10,12,14` but inputs it as `101214`? Your method will then sum it to 9 instead of 36 – Andreas Feb 23 '19 at 12:49
-
well any suggesstion would be appreciated? – Yogesh Raghav Mar 23 '19 at 11:35
3 Answers
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
-
This solution is wrong. Input 2345 comes out as 2345, not the wanted "14" – paskl Feb 23 '19 at 12:14
-
i tested myself bro and than i put the solution.also i haven used any inbuilt functions.if required i will send a working screenshot – Yogesh Raghav Feb 23 '19 at 12:24
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 :)

Yogesh Raghav
- 1
- 1
- 5
-
-
iam having clue mr but just asking about the thing that u mentioned.if u dont wanna contribute than its ok no issue..thanks – Yogesh Raghav Mar 25 '19 at 05:12
-
There is no answer to your question since you have not covered the edge cases as I wrote in the comments to the question. – Andreas Mar 25 '19 at 06:42