Friday, July 3, 2026
HomeLanguagesPHP | DirectoryIterator valid() Function

PHP | DirectoryIterator valid() Function

The DirectoryIterator::valid() function is an inbuilt function in PHP which is used to check the current DirectoryIterator position is a valid file or not.

Syntax:

bool DirectoryIterator::valid( void )

Parameters: This function does not accept any parameters.

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

Below programs illustrate the DirectoryIterator::valid() function in PHP:

Program 1:




<?php
  
// Create a directory Iterator
$directory = new DirectoryIterator(dirname(__FILE__));
  
// Move to the third element
$directory->seek(2);
  
// Check the validity of directory element 
if($directory->valid()) {
  
    // Display the filename
    echo $directory->getFilename();
}
  
?>


Output:

applications.html

Program 2:




<?php
  
// Create a directory Iterator
$directory = new DirectoryIterator(dirname(__FILE__));
  
// Loop runs while directory is valid
while ($directory->valid()) {
      
    // Check for directory element
    if($directory->isDir()) {
  
        // Display the key and filename
        echo $directory->key() . " => " . 
        $directory->getFilename() . "<br>";
    }
  
    // Move to the next element
    $directory->next();
}
  
?>


Output:

0 => .
1 => ..
4 => dashboard
8 => img
11 => webalizer
12 => xampp

Note: The output of this function depends on the content of server folder.

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

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32519 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12015 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6966 POSTS0 COMMENTS