'Sum of numbers from a file in PHP
Given a file with numbers, I need to calculate and display their sum using PHP. This is what I have done so far, but the result displayed is not correct. What am I doing wrong?
<?php
$file = fopen('file.txt', 'r');
$sum = 0;
while(!feof($file)){
$num = (int) fgetc($file);
$sum = $sum + $num;
}
echo $sum;
fclose($file);
?>
The file looks like this:
1 3 10 7 9
Solution 1:[1]
You can create an array of values and return the sum of the array.
$file = fopen('file.txt', 'r');
$values = [];
while(!feof($file)){
$values = array_merge(explode(' ', $file), $values);
}
echo array_sum($values);
fclose($file);
Solution 2:[2]
Alternative answer :
$file = trim(file('file.txt')[0]);
$sum = array_sum(explode(' ', $file));
var_dump($sum);
Solution 3:[3]
try this code, it will work fine
$file = fopen('num.txt', 'r');
$sum = 0;
$lc =0; //last char
$cc = ''; //current char
while(!feof($file)){
$cc = (int) fgetc($file);
if($cc == ' '){
$sum = $lc + $sum;
$lc = ' ';
}else if($cc != ' '){
$lc = $lc+$cc;
}
}
echo $sum;
fclose($file);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | meewog |
| Solution 2 | Wahyu Kristianto |
| Solution 3 | Estail Se |
