Sunday, June 14, 2026
HomeLanguagesPHP | DirectoryIterator getBasename() Function

PHP | DirectoryIterator getBasename() Function

The DirectoryIterator::getBasename() function is an inbuilt function in PHP which is used to get the base name of the current DirectoryIterator item.

Syntax:

string DirectoryIterator::getBasename( string $suffix )

Parameters: This function accepts single parameter $suffix which holds the base name ends with suffix.

Return Value: This function returns the base name of the current DirectoryIterator item.

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

Program 1:




<?php
  
// Create a directory Iterator
$directory = new DirectoryIterator(dirname(__FILE__));
  
// Loop runs while directory is valid
while ($directory->valid()) {
      
    // Display the base name
    echo $directory->getBasename() . "<br>";
  
    // Move to the next element
    $directory->next();
}
?>


Output:

.
..
applications.html
bitnami.css
dashboard
favicon.ico
neveropen.PNG
gfg.php
img
index.php
webalizer
xampp

Program 2:




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


Output:

0 => .
1 => ..
2 => applications.html
3 => bitnami.css
4 => dashboard
5 => favicon.ico
6 => neveropen.PNG
7 => gfg.php
8 => img
9 => index.php
10 => webalizer
11 => xampp

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

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

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS