trauch Posted December 21, 2008 Share Posted December 21, 2008 Im trying to create a stepped php script. Below is an example of the contents of the text file (simple line of numbers) that Im trying to add and write to a new file. The problem is there are spaces in place of commas signifying the thousandths place - any number in the string over 999 incudes a space (ie 1 000) 540 460 1 007 2 000 3 000 4 001 When I use array_sum to add these numbers the total is "1010" when it should be 11,008. This is because it array_sum is only adding the numbers before the space. To address this, I've added the str_replace command before the sum command to remove the spaces. Unfortunately, this does not seem to work. Im not sure if this is because I added the str_replace incorrectly or because the array_sum occurs before the str_replace command happens. The script that Im working with is below. I would appreciate any help. <?php $string = "string to replace all spaces"; $string = str_replace(" ","",$string); $lines = file('textfile.txt/'); echo "sum($lines) = " . array_sum($lines) . "\n"; $lines = file('textfile.txt'); $sum = array_sum($lines); $fp = fopen('total.txt', 'w'); fwrite($fp, $sum); fclose($fp); ?> Link to comment https://forums.phpfreaks.com/topic/137872-solved-str_replace-and-then-array_sum-in-script/ Share on other sites More sharing options...
trauch Posted December 21, 2008 Author Share Posted December 21, 2008 I got it to work. <?php $lines = file('textfile.txt'); $lines = str_replace(' ','',$lines); echo 'sum($lines) = ' . array_sum($lines) . "\n"; $fp = fopen('total.txt', 'w'); $sum = array_sum($lines); fwrite($fp, $sum); fclose($fp); ?> Link to comment https://forums.phpfreaks.com/topic/137872-solved-str_replace-and-then-array_sum-in-script/#findComment-720572 Share on other sites More sharing options...
redarrow Posted December 21, 2008 Share Posted December 21, 2008 Good work grate example. Explain it to others then well done. Link to comment https://forums.phpfreaks.com/topic/137872-solved-str_replace-and-then-array_sum-in-script/#findComment-720650 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.