Jump to content

Writing unique data to text file


jack2119
Go to solution Solved by jcbones,

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
Share on other sites

  • Solution

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.