Open In App

PHP | DirectoryIterator getExtension() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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



Last Updated : 26 Nov, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads