Question: I have a question. I am in process of learning how to read/write files, but having little trouble trying to do both at the same time in same php script. I have a text file with words like this,

```
Richmond,Virginia
Seattle,Washington
Los Angeles,California
Dallas,Texas
Jacksonville,Florida

```

I wrote a code to sort them in order and this will display in sort order by City.

```
<?php
$file = file("states.txt");
sort($file);
for($i=0; $i<count($file); $i++)
{
  $states = explode(",", $file[$i]);
  echo $states[0], $states[1],"<br />";
}
?>

```

From this, how can I rewrite those sorted information back into the states.txt file?

Answer: 
The easiest way to write the contents of `$file` back to the file would be using [`file_put_contents`](http://dk2.php.net/manual/en/function.file-put-contents.php) in collaboration with [`implode`](http://dk2.php.net/manual/en/function.implode.php).

```
file_put_contents("states.txt", implode($file));
```
Try something like this:

```
$fo = fopen("filename", "w");
$content = "";
for ($i = 0; $i < count($file); $i++) {
    $states = explode(",", $file[$i]);
    $content .= $states[0] . "," . $states[1] . "\n";
}
fwrite($fo, $content);
fclose($fo);

```