Friday, May 29, 2026
HomeLanguagesPHP | DirectoryIterator getExtension() Function

PHP | DirectoryIterator getExtension() Function

The DirectoryIterator::getExtension() function is an inbuilt function in PHP which is used to get the file extension.

Syntax:

string DirectoryIterator::getExtension( void )

Parameters: This function does not accept any parameters.

Return Value: This function returns a string which contain the file extension, or an empty string if the file does not contain extension.

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

Program 1:




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


Output:


html
css

ico
PNG
php

php

Note: Empty lines denote the folder which does not contain file extension.

Program 2:




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


Output:

html
css
ico
PNG
php
php

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

Reference: https://www.php.net/manual/en/directoryiterator.getextension.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

1 COMMENT

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6893 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS