Page 1 of 1

str_replace and then array_sum ???

Posted: Sat Dec 20, 2008 9:17 pm
by trauch
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);

?>

Re: str_replace and then array_sum ???

Posted: Sat Dec 20, 2008 9:38 pm
by toasty2
Your code doesn't make sense. Your doing operations on your $string, but its not even used later. Also, if you put a variable inside double quotes( echo "$string"; ) and don't want the value to replace the variable name, use single quotes instead. Variables inside double quotes are evaluated. Please use code tags next time.

Try something like this:

Code: Select all

 
$lines = file('textfile.txt');
$lines = str_replace(' ','',$lines);
echo 'sum($lines) = ' . array_sum($lines) . "\n";
file_put_contents('textfile.txt',$lines);
 

Re: str_replace and then array_sum ???

Posted: Sat Dec 20, 2008 10:07 pm
by trauch
Thanks for the help. I got it to work.

Code: Select all

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