Open In App

PHP SplFileObject next() Function

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

The SplFileObject::next() is an inbuilt function in PHP that is used to iterate the file using the SplFileObject. The pointer will point next line. The SplFileObject implements Iterator and Traversal. That means you can use it in foreach loops and use many of the iterator functions with it.

Syntax

public void SplFileObject::next ( void )

Parameter

This function does not accept any parameters.

Return Value

This function does not return any value.

Program 1: The following program demonstrates the SplFileObject::next() function. Save this text in the “output.txt” file in the current working directory before running this program.

Hey GeeksforGeeks

PHP




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


Output:

Hey GeeksforGeeks

Program 2: The following program demonstrates the SplFileObject::next() function. Save this text in the “output.txt” file in the current working directory before running this program.

Hello
This is a
Simple example
Another example here.

PHP




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


Output:

Simple example
Another example here.

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads