Thursday, September 4, 2025
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
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11857 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS