Jump to content

Writing unique data to text file


jack2119

Recommended Posts

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?

 

 

Link to comment
https://forums.phpfreaks.com/topic/284958-writing-unique-data-to-text-file/
Share on other sites

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.

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.