php - sort the unsorted text file and rewrite to same text file in sorted order

Posted by arrgggg on Stack Overflow See other posts from Stack Overflow or by arrgggg
Published on 2010-04-13T14:35:25Z Indexed on 2010/04/13 14:42 UTC
Read the original article Hit count: 400

Filed under:

Hi, 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?

Thanks for your help.

© Stack Overflow or respective owner

Related posts about php