Open In App

PHP CachingIterator hasNext() Function

Last Updated : 09 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The CachingIterator::hasNext() function is an inbuilt function in PHP that is used to iterate the next element in the iterator. CachingIterator class is to cache the elements of an underlying iterator to improve performance when iterating over the same data multiple times.

Syntax:

public CachingIterator::hasNext(): bool

Parameters: This function does not accept any parameters.

Return Values: This function returns a boolean value true if there is a next element available in the iterator, or false if the iterator has reached the end, and there are no more elements to iterate over.

Program 1: The following program demonstrates the CachingIterator::hasNext() function.

PHP




<?php
  
$data = array('G', 'e', 'e', 'k', 's');
$iterator = new ArrayIterator($data);
  
$cachingIterator = new CachingIterator($iterator);
  
while ($cachingIterator->hasNext()) {
    $current = $cachingIterator->current();
  
    echo $current ;
    $cachingIterator->next();
}
  
?>


Output

Geek

Program 2: The following program demonstrates the CachingIterator::hasNext() function.

PHP




<?php
    
// Sample data
$data = [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 
    12, 13, 14, 15, 16, 17, 18, 19, 20];
  
$iterator = new ArrayIterator($data);
  
$cachingIterator = new CachingIterator($iterator);
  
while ($cachingIterator->hasNext()) {
    $current = $cachingIterator->current();
  
    // Check if the iterator has more elements
    // after the current one
    if ($cachingIterator->hasNext()) {
        echo $current.' ' ;
    
     
    $cachingIterator->next();
}
  
?>


Output

 1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 19 

Reference: https://www.php.net/manual/en/cachingiterator.hasnext.php



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads