Friday, October 17, 2025
HomeLanguagesPHP CachingIterator hasNext() Function

PHP CachingIterator hasNext() Function

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

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS