Home > Software design >  Sum of numbers from a file in PHP
Sum of numbers from a file in PHP

Time:02-25

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

CodePudding user response:

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);

CodePudding user response:

Alternative answer :

$file = trim(file('file.txt')[0]);
$sum = array_sum(explode(' ', $file));

var_dump($sum);
  • Related