PHP | ArrayIterator valid() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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();
}
  
?>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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(); 
     
?>

chevron_right


Output:

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

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.