Write if there is a line, don't write if a line is already..

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cursed
Forum Newbie
Posts: 16
Joined: Sat Aug 26, 2006 10:18 pm

Write if there is a line, don't write if a line is already..

Post by cursed »

Is it possible if I want to write to a file, but if the text is already there, then it wont write to it?

example:
If

Code: Select all

foobar
is in a text file, then
it wont write another same line that says

Code: Select all

foobar
If
foobar is ISNT in the text file, then
foobar would be written on the text file.

Hope this is clear enough!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

You can read the whole file (either with file() or line-by-line via while/fgets) and compare each line. If a line matches skip writing the (not so new) line.

see http://de2.php.net/ref.filesystem
cursed
Forum Newbie
Posts: 16
Joined: Sat Aug 26, 2006 10:18 pm

Post by cursed »

is there a better way?

its hard using lines for me :(
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Code: Select all

if (in_array($string . "\n", file('file.txt'))) {
    echo 'The line ' . $string . ' exists in the file.';
} else {
    echo 'not found';
}
Post Reply