Working with a file

Hello

I have a file data.txt containing some data in this format

house=10
car=12
pen=1
house=10
red table=2
tables=7
house=7
car=7
red table=3
house=3
pen=2

and so on. I need to sum the numeric values of each string to have this result

house=30 car=19 red table=5 tables=7 pen=3 …

Which is the fast way to that using php please ?

Thank you
Graziano

Here is one way to do it.


if(is_file("/TEMP/data.txt")){  // check file exists
$arr = file("/TEMP/data.txt"); // load it line by line into an arrat
$new = array(); // create a blank return array
  foreach($arr as $row){ // loop through the lines in the file

  list($key,$val) = split("=", $row);  // split the line into 2 variables
     if (key_exists($key, $new) ){ // if a key already exists, 
     $new[$key] += (int)$val; // cast the string number an integer, and add it to the existing key
     continue;  // drop out of this part of the loop
     }
  $new[$key] = (int)$val; // other wise add a new key, and assign it the first integer, again casting it with (int)
  }
}


var_dump($new);  // look inside your array

Gives:
array
‘house’ => int 30
‘car’ => int 19
‘pen’ => int 3
‘red table’ => int 5
‘tables’ => int 7

There is probably a other ways of doing this, using fgetcsv maybe, but this should teach you a few basic commands.

Thank you very much, I will try it