Friday, September 5, 2025
HomeLanguagesPHP | DirectoryIterator __construct() Function

PHP | DirectoryIterator __construct() Function

The DirectoryIterator::__construct() function is an inbuilt function in PHP which is used to construct a new directory iterator from a path. 

Syntax:

public DirectoryIterator::__construct( string $path )

Parameters: This function accepts single parameter $path which holds the path of the directory to traverse. 

Return Value: This function does not return any value. 

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

Program 1: 

php




<?php
 
// Create a directory Iterator
$directory = new DirectoryIterator(dirname(__FILE__));
 
// Loop runs for each element of directory
foreach ($directory as $dir) {
 
    // Check if directory element is valid
    if ($dir->valid()) {
 
        // Display the filename
        echo $dir->getFilename() . "<br>";
    }
}
?>


Output:

.
..
applications.html
bitnami.css
dashboard
favicon.ico
neveropen.PNG
gfg.php
img
index.php
Sublime Text Build 3211 x64 Setup.exe
webalizer
xampp

Program 2: 

php




<?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 filename
        echo $directory->getFilename() . "<br>";
    }
 
    // Move to the next element
    $directory->next();
}
?>


Output:

.
..
dashboard
img
webalizer
xampp

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

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6636 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS