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: 
this is a little extended, however I thought it might be useful to smb. I have an m3u playlist and need only particular rows filtered, sorted and printed. Credits go to Devil:

```
<?php

//specify that the variable is of type array
$masiv = array();

//read the file
$file = '/home/zlobi/radio/pls/all.m3u';  

$f = fopen($file, "r");

while ($line = fgets($f))
{
//skip rows with #EXT
if(strpos($line, "#EXT") !== false) continue;

$text = str_replace('.ogg', ' ', $line);  
$text = str_replace('/home/zlobi/radio/',' ',$text);

//add the song as an element in an array
$masiv[] = $text;
}
$f = fclose($f);

//sort the array
sort($masiv);

//pass via the array, take each element and print it
foreach($masiv as $pesen)

print $pesen.'<br/>';

?>

```

masiv is array, pesen is song in Bulgarian :)
CAPital letters are sorted first.

Regads
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.
?>

```