Skip to content
Related Articles

Related Articles

PHP | FilesystemIterator key() Function
  • Last Updated : 26 Nov, 2019

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :