user3419680
user3419680

Reputation: 35

Error with comparison between fgets() to string

I have some file (m.php) that I've just this inside (There is nothing else!):

000

and I have more page with this source:

$file = fopen('m.php', 'a+');
$line = fgets($file);
if ($line == "000") { echo "there is equal"; }
fclose($file);

Why in the if i did not get the "there is equal" ? (it mean: 000 != 000)

but if i do 'echo $line;' , its print to me: 000

Upvotes: 0

Views: 1330

Answers (2)

MarcoS
MarcoS

Reputation: 17711

fgets() returns newline, too... :-) Please chop results before comparing...

<?php
    $file = fopen('m.php', 'a+');
    $line = chop(fgets($file));
    if ($line == "000") {
        echo "there is equal";
    }
    fclose($file);
?>

Upvotes: 0

user3383116
user3383116

Reputation: 392

Or you can do it like this

<?php
    $file = 'm.php';
    $line = file_get_contents($file);
    if ($line == "000") {
        echo "there is equal";
    }
?>

Upvotes: 1

Related Questions