add numbers in a list in a txt file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
trauch
Forum Newbie
Posts: 14
Joined: Thu Dec 11, 2008 4:50 pm

add numbers in a list in a txt file

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: add numbers in a list in a txt file

Post 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()
trauch
Forum Newbie
Posts: 14
Joined: Thu Dec 11, 2008 4:50 pm

Re: add numbers in a list in a txt file

Post 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?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: add numbers in a list in a txt file

Post 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 :)
trauch
Forum Newbie
Posts: 14
Joined: Thu Dec 11, 2008 4:50 pm

Re: add numbers in a list in a txt file

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: add numbers in a list in a txt file

Post 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.
Post Reply