Thursday, September 4, 2025
HomeLanguagesPHP SplFileObject key() Function

PHP SplFileObject key() Function

The SplFileObject::key() is an inbuilt function of the Standard PHP Library (SPL) in PHP that is used to get the key (line number) of the current line pointed to by the SplFileObject.

Syntax

public SplFileObject::key(): int

Parameter

This function does not have any parameters.

Return Value

The SplFileObject::key() function returns the current line number in the form of an integer. The first line starts from 0 and the second line number is 1.

Program 1: The following program demonstrates the SplFileObject::key() function. Before running this program you must save this file (“output.txt”) in your current working directory.

PHP




<?php
  
$file = new SplFileObject("./output.txt", "r");
  
while (!$file->eof()) {
    
    // Get the current line
    $line = $file->current();
    $lineNumber = $file->key();
    echo "Line $lineNumber: $line" . PHP_EOL;
    
    // Advance to the next line
    $file->next();
}
?>


output.txt:

This is a text
Simple example
Another example here

Output:

Line 0: This is a text 
Line 1: Simple example 
Line 2: Another example here

Program 2: The following program demonstrates the SplFileObject::key() function. Before running this program you must save this file (“output.txt”) in your current working directory.

PHP




<?php
$file = new SplFileObject("./output.txt", "r");
  
while (!$file->eof()) {
    $lineNumber = $file->key();
    
    // Get the current line content
    $line = $file->current();
  
    if ($lineNumber % 2 === 0) {
        
        // Check if the line number is even
        echo "Line $lineNumber: $line" . PHP_EOL;
    }
  
    $file->next();
}
?>


output.txt:

Line 1
Line 2
Line 3
Line 4
Line 5

Output:

Line 0: Line 1
Line 2: Line 3
Line 4: Line 5

Reference: https://www.php.net/manual/en/splfileobject.key.php

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32262 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11856 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS