faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

32 of 37 people (86%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do I read out data from a text file line by line, and compare each line with a certain variable?

May 21st, 2001 08:12
Philip Olson, Philipp Hartmann,


Simplest way is to use the file() function as it will turn each line 
into an element of an array, such as $lines.  From there we loop 
through with foreach and within the loop compare the $variable with the 
text within the line.  We'll use trim() to trim off any potential 
whitespace that may get into the way of our comparison.  Break 
essentially ends/breaks the loop after the first match.
    $lines = file($filename);
    foreach ($lines as $line_number => $line_text) {
        if ($variable == trim($line_text)) {
            echo "$line_number : match!";
            break;
        }
    }
For a case insensitive match, consider strcasecmp() and you'll replace :
    if ($variable == trim($line_text)) {
With :
    if (strcasecmp($variable,trim($line_text)) == 0) {
We compare to 0 as if they are equal, it strcasecmp returns 0.  Now if 
you're wanting to get all matches as opposed to just the first, put 
them into an array, replace :
    echo "$line_number : match!";
    break;
With :
    $matches[] = $line_number;
Now $matches array will contain all line numbers that match your 
$variable.
Now, let's say you wanted to stop at the first match, like the first 
example, and be faster and more efficient.  Then you can do this :
    $count = 1;
    while ($line_text = fgets($fp, 2048)) {
        if ($variable = trim($line_text)) {
            echo "Match at line number $count";
            break;
        }
    ++$count;
    }
As it doesn't initially load the entire file, just one line at a time, 
which is what file() does.  Then we use 'break' so whatever is after 
the match is never read.  The 2048 within fgets() function is 
essentially the maximum number of bytes fgets will read per line, set 
this accordingly.
Related PHP manual entries :
  http://www.php.net/manual/en/function.file.php
  http://www.php.net/manual/en/function.fgets.php
  http://www.php.net/manual/en/function.strcasecmp.php
  http://www.php.net/manual/en/control-structures.break.php
  http://www.php.net/manual/en/control-structures.foreach.php