Home > Software engineering >  Simple string comparison shows wrong results
Simple string comparison shows wrong results

Time:10-26

It sounds very simple and it should be but I've got some issue and can't find it.

I have a file with words on each line, like

dog
dog
dog
dogfirend
dogandcat
dogcollar
dog-food

The above should display me: 3 (since there are only 3 full matches of dog)

I'm trying to read the file and check how many times the word dog is inside. The problem is that it doesn't count at all and shows 0. This is what I have

$word = "dog";
$count = 0;

$handle = fopen("dogs.txt", "r");
if ($handle) {
    
    while (($line = fgets($handle)) !== false) {
        if ($word == $line) {
             $count  ;
        }      
    }
    fclose($handle);
}

CodePudding user response:

The lines in your file are separated by a newline. This newline is included in your $line variable.

From the fgets() manual: "Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first)."

You need to trim() your $line first, so those characters get removed:

$word = "dog";
$count = 0;
$handle = fopen("dogs.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if ($word == trim($line)) {
             $count  ;
        }      
    }
    fclose($handle);
}
echo $count
  •  Tags:  
  • php
  • Related