PHP Program to Sum Only Numeric Tokens with Explanation
PHP
Medium
PHP Data Types
25 views
1 min read
100 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around sum, token, only. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given a line with mixed tokens, add only the numeric ones and print the sum. Print as integer if it is whole.
Input Format
One line with tokens.
Output Format
One number sum.
Constraints
Total text
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$parts=preg_split('/\\s+/', $inputText);
$sum=0.0;
foreach($parts as $t){
if($t==='') continue;
if(is_numeric($t)) $sum+=floatval($t);
}
if(abs($sum-round($sum))<1e-9) echo strval(intval(round($sum)));
else{
$s=rtrim(rtrim(number_format($sum,10,'.',''),'0'),'.');
echo $s;
}
?>
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Given a line with mixed tokens, add only the numeric ones and print the sum. Print as integer if it is whole.
Input / Output
Input
One line with tokens.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$parts=preg_split('/\\s+/', $inputText);
$sum=0.0;
foreach($parts as $t){
if($t==='') continue;
if(is_numeric($t)) $sum+=floatval($t);
}
if(abs($sum-round($sum))<1e-9) echo strval(intval(round($sum)));
else{
$s=rtrim(rtrim(number_format($sum,10,'.',''),'0'),'.');
echo $s;
}
?>
Solutions (0)
No solutions submitted yet. Be the first!