I have the following code:
$array_test = array();
$file = file_get_contents ('./test.txt');
$file_array = explode("\n", $file);
foreach ($file_array as $line) {
$word = trim($line);
$array_test[] = $word;
}
echo $array_test[0];
if ($array_test[0] == "1") { echo 'first line'; }
echo $array_test[1];
if ($array_test[1] == "2") { echo 'second line'; }
print_r ($array_test);
The test.txt is file encoded in UTF-8. It has 5 lines. On each line I have a number: 1 - first line, 2 - second line, etc.
The result of running the script is as follows:
1
2
second line
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
As you can see there's a problem with the first line. It seems that it was added to the array correctly, but somehow its value differs from "1". There's no problems with the other lines, just the first one. The problem can be fixed by skipping the first line and starting to add to the array the values from the second line, but I'm just wondering why it doesn't work the way I wrote it? Usually I don't have any problems with displaying or reading UTF8 encoded texts or pages. Changing to "file" instead of "file_get_contents" doesn't solve the problem. Any suggestion would be very appreciated. p.s. PHP Version 5.3.1
UPDATE: The problem was UTF-8 BOM. See the solution below. Thanks everybody for the help!
The main issue is this but I am not able to solve it yet. On var_dump($array_test[0]) I get the following output:
This is the reason 'first line' is not echoed as the if condition is not getting true.
Also if you can share your
test.txt
file it will be easy to catch the problem.EDIT : Partial Solution
You can add this line before first if condition to handle this behaviour as described by @Tino Didriksen to get your desired output.
Please try below updated code:
(Try doing) -- wrong solution. see below
and there is one function file() for such cases:
I was WRONG!
var_dump gives us an answer:
there is new line character in the string.
try doing: