Jump to content

Alphabetizing A Text File


Grabeorama

Recommended Posts

Use file() to read the file into an array.Use sort() to alphabetize the array. -- But investigate what natsort() and natcasesort() do.Use implode() to turn the array into a stringWrite the string to a file using any of several methods. file_put_contents() works if you have PHP 5 or better. Otherwise use fopen() and fwrite().

Link to comment
Share on other sites

Ok, thanks I'll try thatEDIT:This is my code:

<html>	<head>		<title>Test page</title>	</head>	<body>		<p>Test Page</p>		<?php			$text 		= 'animals.txt';			$new_array 	= file($text);			$new_array	   = natcasesort($new_array);			$new_array	   = implode($new_array);			echo $new_array;		?>	</body></html>

and here is the output I got:Test PageArrayand here's the contents of 'animals.txt':"Dog, Cat, Mouse, Lion, Tiger, Rat"Is there a certain way of writing animals.txt? Do I leave out the comas?

Link to comment
Share on other sites

the file() command reads each line of a document as an element of the array, so separate the elements with line breaks, not commas.If you put them all on one line separated by commas you'll have to use a different method to extract it from the file and turn it into an array.When using implode() specify a separating character, like "," or a line break:

implode(",",$file_array);

Otherwise no character will be put between the elements.

Link to comment
Share on other sites

  • 3 weeks later...

OK, this is my new code, but still returns an error:

<html><head>	<title>Array Sort</title></head><body>	<?php		$file		  = "review_list_a.txt"		$new_array 	= file($file);		$new_array 	= natcasesort($new_array);		$new_array  = implode(",",$new_array);		echo $new_array;	?></body></html>

It returns:Parse error: parse error, unexpected T_VARIABLE in /home/content/k/g/r/kgrabe/html/grabeorama/test.php on line 10Any ideas as to why?Thanks :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...