Open In App

PHP | ArrayIterator valid() Function

Last Updated : 21 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The ArrayIterator::valid() function is an inbuilt function in PHP which is used to check whether an array contains more entries or not.

Syntax:

bool ArrayIterator::valid( void )

Parameters: This function does not accept any parameters.

Return Value: This function returns TRUE if the iterator is valid, FALSE otherwise.

Below programs illustrate the ArrayIterator::valid() function in PHP:
Program 1:




<?php
  
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
    array('G', 'e', 'e', 'k', 's')
);
  
while ($arrItr->valid()) {
    echo "ArrayIterator Key: " . $arrItr->key() .
    "  ArrayIterator Value: " . $arrItr->current() . "\n";
      
    $arrItr->next();
}
  
?>


Output:

ArrayIterator Key: 0  ArrayIterator Value: G
ArrayIterator Key: 1  ArrayIterator Value: e
ArrayIterator Key: 2  ArrayIterator Value: e
ArrayIterator Key: 3  ArrayIterator Value: k
ArrayIterator Key: 4  ArrayIterator Value: s

Program 2:




<?php
     
// Declare an ArrayIterator
$arrItr = new ArrayIterator(
    array(
        "a" => "Geeks",
        "b" => "for",
        "c" => "Geeks"
    )
);
  
// Using rewind function 
$arrItr->rewind(); 
      
while($arrItr->valid()) { 
    var_dump($arrItr->current()); 
          
    // Moving to next element 
    $arrItr->next(); 
     
?>


Output:

string(5) "Geeks"
string(3) "for"
string(5) "Geeks"

Reference: https://www.php.net/manual/en/arrayiterator.valid.php



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads