phpllama Posted July 25, 2009 Share Posted July 25, 2009 file.txt Lemon,222 Apple,444 Orange,5353 Basically I want the PHP code to choose a random line from the text file and setup 2 values ($word, $number) using the comma as the seperator. But how do you seperate using the comma? Link to comment https://forums.phpfreaks.com/topic/167356-sorting-a-textfile/ Share on other sites More sharing options...
vineld Posted July 25, 2009 Share Posted July 25, 2009 Use explode Link to comment https://forums.phpfreaks.com/topic/167356-sorting-a-textfile/#findComment-882480 Share on other sites More sharing options...
jonsjava Posted July 25, 2009 Share Posted July 25, 2009 if you want to see a working example: <?php $file = "yourfile.txt"; //declare your file name here $fh = fopen($file, "r"); // this opens the text file in read-only $data = fread($fh, filesize($file)); // this takes all the data in the file, and puts it into a variable fclose($fh); //and we close the file $data_array = explode("\n", $data); //we separate each line into an array $end = count($data_array) - 1; // we find the end of the array $rand = rand(0,$end); // we randomly pick a line in the array $rand_s = explode(",", $data_array[$rand]); //we separate all data from the selected item, based on the "," print "({$rand_s[0]},{$rand_s[1]})"; // we now have the data. ?> Link to comment https://forums.phpfreaks.com/topic/167356-sorting-a-textfile/#findComment-882482 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.