# Add up rows of numbers in text file - PHP



## Moatist (Dec 17, 2008)

Hey everyone,

How do you add up all the numbers in a text file if each number was on a different row? I would like to do this through PHP.

Thanks ahead of time,
Moatist

---Edit---

The numbers don't have to be in separate row if that would help.


----------



## Redcore (Aug 14, 2007)

```
$file = "yourfile.txt";
echo count(file($file));
```


----------



## YorkshireSteve (Jan 2, 2009)

Hi,

The last solution gives you the total number of lines in the file, which I don't think it what you're looking to do...

First you need to get the contents of the file...


```
$filename = "myfile.txt";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($handle);
```
$contents now has everything from the file. Next you need to seperate out all of the separate values in the file. You can either use the split() function, of use preg_match_all() if the file contains other stuff as well.


```
$numbers = split("\r\n", $contents); // Use "\r\n" for Windows, "\n" for Unix

$total = 0;

foreach ($numbers as $number) {
    $total += $number;
}

echo $total;
```


----------

