jack2119 Posted December 29, 2013 Share Posted December 29, 2013 Hi, I'm writing the following data to a text file. "name|price|image|text". The following code does exactly that. $filename = 'test.txt'; // Read file in to array. Each element is a line. $lines = file($filename, FILE_IGNORE_NEW_LINES); $data_to_add = $somecontent; // If the new data does not exist in the array if(!in_array($data_to_add, $lines)) { unset($lines[11]); // delete the 10th line array_unshift($lines, $data_to_add); // Put new data at the front of the array // Write the new array to the file file_put_contents($filename, implode("\n", $lines)); } I'm not sure what I ahve to do to make sure that the arrray only searches the first part of the data which in this case is "name" to make sure only unique data is saved? Quote Link to comment https://forums.phpfreaks.com/topic/284958-writing-unique-data-to-text-file/ Share on other sites More sharing options...
Solution jcbones Posted December 29, 2013 Solution Share Posted December 29, 2013 Instead of !in_array(), pass the $data_to_add to this function instead. function uniqueName($data,$lines) { $name = explode('|',$data); //separate the name out of the pipe delimited list; foreach($lines as $line) { //go through each line of data; if(substr($line,0,strlen($name[0])) === $name[0]) { //test for the first word to match $name; return false; //if it does, it isn't unique, so return false; } } return true; //if it doesn't return true, because it truly is unique. } Of course, test it for yourself. *note* depending on array size, testing for uniqueness in a file could take a while. That is why databases are always suggested, as they are optimized for this task. Quote Link to comment https://forums.phpfreaks.com/topic/284958-writing-unique-data-to-text-file/#findComment-1463221 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.