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: 
Try using fopen and fwrite. 

```
$fileWrite = fopen("filePah", "w");

for($i=0; $i<count($file); $i++)
{
    fWrite($fileWrite, $file[i]);
}
fClose($fileWrite);

```
Once you are done reading the file into the array by a call to [file](http://php.net/manual/en/function.file.php). You can open the file for writing by using the [fopen](http://php.net/manual/en/function.fopen.php) function, write into the file using the [fwrite](http://php.net/manual/en/function.fwrite.php) and close the file handle using [fclose](http://php.net/manual/en/function.fclose.php):

```
<?php
$file = file("states.txt");                  // read file into array.
$fh = fopen('states.txt','w') or die("..."); // open same file for writing.
sort($file);
for($i=0; $i<count($file); $i++)
{
    $states = explode(",", $file[$i]);
    echo $states[0], $states[1],"<br />";
    fwrite($fh,"$states[0],$states[1] <br />"); // write to file.
}
fclose($fh); // close file.
?>

```