Search code examples
phpstringcomparison

PHP string comparison of same word problem


I am opening some files with fopen and in these files i read a word and put it in a variable. The word is "hour" . But later when i compare this variable with the word "hour" it doesnt return equal ! The problem may have something to do with the encoding. Is there any way to format the encoding so it matches with the common text?

Here is a sample of the code refering to the problem i am facing:

$myfile = fopen("/hdd4/no2_2013_2016/".$files[$i], "r") or die("Unable to open file!");
$raw_text=fgets($myfile)
$text_array=explode(",",$raw_text);
$frequency=$text_array[10];  // It is hour and it reads it correctly as i echoed it
echo strcmp($frequency, "hour"); // not 0 ,in fact it returns -104 .Also the number my differ with other files

if ($frequency=="hour") //also doesn't work

As suggested I used var_dump($frequency) and it returned:

string(9) "\000h\000o\000u\000r\000"

After trim($frequency) it returned:

string(7) "h\000o\000u\000r"

Solution

  • That is a null character before each character. If you are creating the file then you are not doing it properly. Presumably something is putting one character at a time to the file and each put is terminated by a null character, or that happened in a previous step.

    If it is outside of your control then replace that character:

    $raw_text = str_replace("\0", "", fgets($myfile));