fgets

fgets(resource $stream, ?int $length = null): string|false

Line-by-line reading: PHP fgets keeps the trailing newline in the return value (length-1 cap) and returns false at EOF - whether each language keeps the newline is the core teaching point.

C C23

C23
#include <stdio.h>

int main(void) {
    // fgets keeps the trailing "\n" (up to length-1 bytes) - PHP inherited this
    FILE *w = fopen("demo.txt", "w");
    fputs("alpha\nbeta\ngamma", w);
    fclose(w);

    FILE *h = fopen("demo.txt", "r");
    char line[32];
    int count = 0;
    while (fgets(line, sizeof line, h) != NULL) {
        count++;
        printf("line %d: ", count);
        for (char *p = line; *p != '\0'; p++) {
            if (*p == '\n') {
                printf("\\n"); // reveal the kept newline
            } else {
                putchar(*p);
            }
        }
        printf("\n");
    }
    fclose(h);
    return 0;
}
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

C++ C++26

C++26
#include <fstream>
#include <iostream>
#include <string>

int main() {
    // std::getline strips the "\n" - the opposite choice from fgets
    {
        std::ofstream w("demo.txt");
        w << "alpha\nbeta\ngamma";
    }
    std::ifstream h("demo.txt");
    std::string line;
    int count = 0;
    while (std::getline(h, line)) {
        count++;
        std::cout << "line " << count << ": " << line;
        if (!h.eof()) {
            std::cout << "\\n"; // a non-eof line ended with a newline that getline removed
        }
        std::cout << "\n";
    }
}
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

C# v11.0.100

v11.0.100
// StreamReader.ReadLine strips the newline; Peek() tells whether more data follows
using System.IO;

File.WriteAllText("demo.txt", "alpha\nbeta\ngamma");
using (StreamReader r = new StreamReader("demo.txt")) {
    int count = 0;
    string? line;
    while ((line = r.ReadLine()) != null) {
        count++;
        bool hadNl = r.Peek() != -1; // more data means this line ended with "\n"
        Console.WriteLine($"line {count}: {line}{(hadNl ? "\\n" : "")}");
    }
}
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

Go v1.27.4

v1.27.4
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	// bufio.Reader.ReadString keeps the delimiter - the fgets behaviour
	f, _ := os.Create("demo.txt")
	f.WriteString("alpha\nbeta\ngamma")
	f.Close()

	f, _ = os.Open("demo.txt")
	defer f.Close()
	reader := bufio.NewReader(f)
	count := 0
	for {
		line, err := reader.ReadString('\n') // keeps the "\n"
		if len(line) > 0 {
			count++
			marker := ""
			if strings.HasSuffix(line, "\n") {
				marker = "\\n"
			}
			fmt.Printf("line %d: %s%s\n", count, strings.TrimSuffix(line, "\n"), marker)
		}
		if err != nil {
			break // io.EOF after the last (newline-less) line
		}
	}
}
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

Java v27.0.1

v27.0.1
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws Exception {
        // BufferedReader.readLine strips the newline; ready() reports more data
        Files.writeString(Path.of("demo.txt"), "alpha\nbeta\ngamma");
        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("demo.txt"), StandardCharsets.UTF_8));
        int count = 0;
        String line;
        while ((line = r.readLine()) != null) {
            count++;
            String marker = r.ready() ? "\\n" : ""; // more data means this line ended with "\n"
            System.out.println("line " + count + ": " + line + marker);
        }
        r.close();
    }
}
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

JavaScript v26.13.1

v26.13.1
// Node has no stdio line iterator like fgets; the deterministic equivalent is split on "\n"
const fs = require("node:fs");
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
const content = fs.readFileSync("demo.txt", "utf8");
const lines = content.split("\n"); // no trailing "\n" here, so no empty tail piece
lines.forEach((line, i) => {
    const hadNl = i < lines.length - 1; // every piece but the last ended with "\n"
    console.log(`line ${i + 1}: ${line}${hadNl ? "\\n" : ""}`);
});
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

PHP v8.6.0

v8.6.0
// fgets INCLUDES the trailing "\n" in the returned string (unless EOF cuts it)
file_put_contents("demo.txt", "alpha\nbeta\ngamma");
$h = fopen("demo.txt", "r");
$count = 0;
while (($line = fgets($h)) !== false) {
    $count++;
    $hadNl = str_ends_with($line, "\n"); // PHP keeps it - unlike most other languages
    echo "line $count: ", rtrim($line, "\n"), $hadNl ? "\\n" : "", "\n";
}
fclose($h);
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

Python v3.15.2

v3.15.2
# Iterating a file object yields lines WITH their "\n" - the fgets behaviour
with open("demo.txt", "w") as f:
    f.write("alpha\nbeta\ngamma")
with open("demo.txt") as f:
    for count, line in enumerate(f, 1):
        had_nl = line.endswith("\n")  # kept, like fgets
        marker = "\\n" if had_nl else ""
        print(f"line {count}: {line.rstrip()}" + marker)
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

Rust v1.99.1

v1.99.1
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    // BufRead::read_line keeps the "\n"; BufRead::lines would strip it
    std::fs::write("demo.txt", "alpha\nbeta\ngamma").unwrap();
    let mut h = BufReader::new(File::open("demo.txt").unwrap());
    let mut line = String::new();
    let mut count = 0;
    loop {
        line.clear();
        let n = h.read_line(&mut line).unwrap();
        if n == 0 {
            break; // EOF
        }
        count += 1;
        let had_nl = line.ends_with('\n');
        print!("line {}: {}", count, line.trim_end_matches('\n'));
        if had_nl {
            print!("\\n");
        }
        println!();
    }
}
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

TypeScript v26.13.1

v26.13.1
// Node has no stdio line iterator like fgets; the deterministic equivalent is split on "\n"
import * as fs from "node:fs";
fs.writeFileSync("demo.txt", "alpha\nbeta\ngamma");
const content: string = fs.readFileSync("demo.txt", "utf8");
const lines: string[] = content.split("\n"); // no trailing "\n" here, so no empty tail piece
lines.forEach((line: string, i: number) => {
    const hadNl: boolean = i < lines.length - 1;
    console.log(`line ${i + 1}: ${line}${hadNl ? "\\n" : ""}`);
});
Output
line 1: alpha\n
line 2: beta\n
line 3: gamma

Language differences

C: fgets keeps the newline (including "\n"); the length-1 cap prevents buffer overflow - the prototype of PHP's semantics.

C++: std::getline strips the newline; EOF/failure falsifies the loop condition.

C#: ReadLine strips the newline; Peek() == -1 marks a final line without newline.

Go: bufio.Reader.ReadString keeps the delimiter; bufio.Scanner is also line-level but strips newlines as token semantics.

Java: readLine strips the newline; ready() reports whether more data is buffered.

JavaScript: no built-in line iterator (readline is an event stream); read-then-split is the deterministic equivalent.

PHP: fgets includes the newline - use FILE_IGNORE_NEW_LINES (file entry) or rtrim for a clean line; the length parameter truncates to length-1 bytes.

Python: the file iterator keeps the newline; str.rstrip() is the common cleanup.

Rust: read_line keeps the newline (the String ends with "\n"); the lines() iterator strips it.

TypeScript: same as JavaScript.