Open In App

PHP SplFileObject key() Function

Last Updated : 28 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads