Jump to content

[SOLVED] str_replace and then array_sum ??? in script


trauch

Recommended Posts

 

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

 

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.