harryz
harryz

Reputation: 5280

Why EOF of file not work in my PHP code?

I'm writing a PHP program to read a passwd file like below:

  1 misshary:x:1002:1003:Li Han,Li Han,,:/home/misshary:/bin/bash
  2 testuser:x:1003:1004:test user,,,:/home/testuser:/bin/bash   

And here is my code:

        $file = fopen("/path/passwd.bak", "r") or exit("Unable to open passwd file!");

        while(!feof($file))
            {
                $user_line = fgets($file);
                $user_array = explode(":", $user_line);

                echo print_r( $user_array)."</br>";
            }

But what I got is:

Array ( [0] => misshary [1] => x [2] => 1002 [3] => 1003 [4] => Li Han,Li Han,, [5] =>      /home/misshary [6] => /bin/bash ) 1
Array ( [0] => testuser [1] => x [2] => 1003 [3] => 1004 [4] => test user,,, [5] => /home/testuser [6] => /bin/bash ) 1
Array ( [0] => ) 1

Why I got a extra line and result in a extra array Array ( [0] => ) here?

P.S I understand why there is a extra 1 followed. My question is that why there are three arrays printed.

Upvotes: 0

Views: 370

Answers (2)

xdazz
xdazz

Reputation: 160883

Because you did echo print_r( $user_array), print_r already did print the data out and no need to use echo.

print_r:

When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.

so you echo the result of print_r, which is true and converted into 1.

And you may skip the empty lines and ignore the new lines in the file by using file() function:

$lines = file('/path/passwd.bak', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

if (!$lines) {
  exit("Unable to open passwd file!");
}

foreach ($lines as $line) {
  $user_array = explode(":", $line);
  var_dump($user_array);
}

Upvotes: 0

arcyqwerty
arcyqwerty

Reputation: 10695

Are you sure there is no newline character at the end of your passwd file?

As for the extra 1 at the end its because you are printing the result of print_r

Since print_r already prints the array you should just use print_r( $user_array)."</br>"; without the echo

As per the docs:

When the return parameter is TRUE, this function will return a string. Otherwise, the return value is  TRUE.

Upvotes: 1

Related Questions