PHP SplFileObject key() Function
Last Updated :
28 Sep, 2023
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()) {
$line = $file ->current();
$lineNumber = $file ->key();
echo "Line $lineNumber: $line" . PHP_EOL;
$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();
$line = $file ->current();
if ( $lineNumber % 2 === 0) {
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
Share your thoughts in the comments
Please Login to comment...