Jay Lin
Jay Lin

Reputation: 49

PHP: fread and the newline character

If I make a simple text file such as the following:

first line.
second line.

And apply fread in the following way:

$fh = fopen("test_file_three.txt",'r') or die("Error attempting to 
open file.");
$first_word = fread($fh,5);
$second_word = fread($fh,6);
$third_word = fread($fh,1);
$fourth_word = fread($fh,3);
echo $first_word;
echo "<br />";
echo $second_word;
echo "<br />";
echo $third_word;
echo "<br />";
echo $fourth_word;
echo "<br />";

The echo of the $third_word variable is just, as expected, "blank". I assume it takes in and stores the new line character. However, if I append the following code:

if ($third_word === '\n'){
    echo "Third word is newline character.";
}
else {
    echo "Third word is not newline character.";
}

(or, alternatively, == instead of ===) Then it comes out as false; testing $newline_char = '\n'; in such an if statement, however, works fine. What is happening here?, is a newline character being stored?

Upvotes: 1

Views: 809

Answers (2)

Marco
Marco

Reputation: 7287

I assume it takes in and stores the new line character.

Your assumption is correct.

Depending on how you created the file it will be \n (on Unix, OS X) or \r\n (Windows).

Make sure to check your editor's line ending character.

What is happening here?

Your if evaluates to false because '\n' means literally a backslash and an n character.

Use double quotes to get the newline character: "\n" and your if should evaluate to true.

What is the difference between single-quoted and double-quoted strings in PHP?


I really recommend you use a hexdump function, this way you know exactly what's stored inside a string.

Here's an implementation of a hexdump function.

Adjusting your code with calls to hex_dump instead of echo:

hex_dump($first_word);
hex_dump($second_word);
hex_dump($third_word);
hex_dump($fourth_word);

Gives me the following:

 0 : 66 69 72 73 74 [first]
 0 : 20 6c 69 6e 65 2e [ line.]
 0 : 0a [.]
 0 : 73 65 63 [sec]

You can see $third_word consists of a single byte 0x0a, which is the binary representation for the newline character (\n).

Upvotes: 1

suchislife
suchislife

Reputation: 1

PHP Comparison Operators

The === operator checks for the value and the type.

$x === $y Returns true if $x is equal to $y, and they are of the same type

Upvotes: 0

Related Questions