Content · Programming · PHP

PHP feof() Function: Usage and Examples

Learn how PHP feof works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Indicates whether a file stream has reached its end.

What Is feof() in PHP?

Indicates whether a file stream has reached its end.

Its syntax is:

feof(resource $stream): bool

Parameters:

  • $stream — Accepted as resource; required argument.

Return type: bool. Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.

Availability: Requires an open stream.

Example 1: Basic Usage

<?php

$stream = fopen("php://memory", "r+"); fwrite($stream, "abc"); rewind($stream); var_dump(feof($stream)); fclose($stream);

Output:

bool(false)

Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.

Example 2: A Different Input

<?php

$stream = fopen("php://memory", "r+"); fwrite($stream, "A"); rewind($stream); fgetc($stream); fgetc($stream); var_dump(feof($stream)); fclose($stream);

Output:

bool(true)

Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.

Practical Example: Applying It in a Program

<?php

$stream = fopen("php://memory", "r+"); fwrite($stream, "one\ntwo\n"); rewind($stream); while (($line = fgets($stream)) !== false) { echo trim($line) . PHP_EOL; } fclose($stream);

Output:

one
two

Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.

Important Behavior and Edge Cases

  • Key behavior: Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.
  • Environment: Requires an open stream.

Comparison With Related Functions

FunctionPurpose
feof()Indicates whether a file stream has reached its end.
fgets()fgets() reads a line; feof() checks whether a file stream reached end of file.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the endUse the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.

Key Takeaways

  • Indicates whether a file stream has reached its end.
  • Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.
  • Requires an open stream.

Summary: Use the return value of fgets()/fread() in loops; feof() may become true only after an attempted read beyond the end.

Share this resourceSend this page to someone who may find it useful.