Page 1 of 1

add numbers in a list in a txt file

Posted: Fri Dec 19, 2008 10:43 pm
by trauch
I have a .txt file on my server that contains about 30 lines of distinct numbers. This file is overwritten each day and I would like to create a script that adds all the numbers in the text file and writes the total to a new txt file each day. I'm sure this is pretty simple and would greatly appreciate someone sending me a sample script.

Below is an example of the contents of the text file. There is nothing but text in the file.
45
63
54
23
45


Thanks in advance.

Re: add numbers in a list in a txt file

Posted: Fri Dec 19, 2008 11:01 pm
by John Cartwright
Indeed it is pretty straight forward. Simply load file into array, sum the values, and write to a new text file?

Code: Select all

$sum = array_sum(file('/path/to/file.txt'));
.. and then fopen() + fwrite() or file_put_contents()

Re: add numbers in a list in a txt file

Posted: Sat Dec 20, 2008 2:29 pm
by trauch
Thanks for your help. I have got the code to work but am not sure how to write to a new txt file. Here's what I've got so far.

<?php
$lines = file('textfile.txt/');
echo "sum($lines) = " . array_sum($lines) . "\n";
?>

I tried to use "put_file_contents" but either I messed it up or possibly this doesnt work with php4???

Can you help with this?

Re: add numbers in a list in a txt file

Posted: Sat Dec 20, 2008 2:36 pm
by John Cartwright
Indeed file_put_contents() is php5 only. Take a look at the fopen() and fwrite() in my last post as a php4 alternative. They have a ton of examples :)

Re: add numbers in a list in a txt file

Posted: Sat Dec 20, 2008 3:10 pm
by trauch
Thanks again.

To say Im a newbie is being generous. I understand fopen and fwrite and used them in a basic open & write script but Im not sure how to associate the commands with this script. Can you help, AGAIN.

Thanks a bunch

Re: add numbers in a list in a txt file

Posted: Sat Dec 20, 2008 3:20 pm
by John Cartwright
I have no problem helping you. All I ask is you try first, then ask questions later. There are a million examples on those two links I gave you (dont forget to user the user comments as well). Give a couple of them a try and post back your results and/or errors that you have questions about.

Good luck.