Monday, June 15, 2026
HomeLanguagesPHP | FilesystemIterator key() Function

PHP | FilesystemIterator key() Function

The FilesystemIterator::key() function is an inbuilt function in PHP which is used to retrieve the key for the current file.

Syntax:

string FilesystemIterator::key( void )

Parameters: This function does not accept any parameters.

Return Value: This function returns the pathname or filename depending on the set flags.

Below programs illustrate the FilesystemIterator::key() function in PHP:

Program 1:




<?php
  
// Create new file system iterator
$fileItr = new FilesystemIterator(dirname(__FILE__), 
        FilesystemIterator::KEY_AS_FILENAME);
  
// Loop runs for each element of file iterator
foreach($fileItr as $it) {
  
    // Display the key
    echo $fileItr->key() . "<br>"; 
}
  
?>


Output:

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

Program 2:




<?php
  
// Create new file system iterator
$fileItr = new FilesystemIterator(dirname(__FILE__), 
        FilesystemIterator::KEY_AS_FILENAME);
  
// Loop runs while file iterator is valid
while ($fileItr->valid()) {
  
    // Check for non directory files
    if (!$fileItr->isDir()) {
  
        // Display the key
        echo $fileItr->key() . "<br>"; 
    }
  
    // Move to the next element
    $fileItr->next();
}
  
?>


Output:

applications.html
bitnami.css
favicon.ico
gfg.php
index.php

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

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