Friday, February 13, 2026
HomeLanguagesPHP | DirectoryIterator key() Function

PHP | DirectoryIterator key() Function

The DirectoryIterator::key() function is an inbuilt function in PHP which is used to return the key for the current DirectoryIterator item.

Syntax:

string DirectoryIterator::key( void )

Parameters: This function does not accept any parameters.

Return Value: This function returns the key for the current DirectoryIterator item.

Below programs illustrate the DirectoryIterator::key() 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 key and filename
    echo $dir->key() . " => " . 
    $dir->getFilename() . "<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 => Sublime Text Build 3211 x64 Setup.exe
11 => webalizer
12 => xampp

Program 2:




<?php
  
// Create a directory Iterator
$directory = new DirectoryIterator(dirname(__FILE__));
  
// Loop runs while directory is valid
while ($directory->valid()) {
      
    // Check for directory element
    if($directory->isDir()) {
  
        // Display the key and filename
        echo $directory->key() . " => " . 
        $directory->getFilename() . "<br>";
    }
  
    // Move to the next element
    $directory->next();
}
  
?>


Output:

0 => .
1 => ..
4 => dashboard
8 => img
11 => webalizer
12 => xampp

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

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32499 POSTS0 COMMENTS
Milvus
128 POSTS0 COMMENTS
Nango Kala
6878 POSTS0 COMMENTS
Nicole Veronica
12000 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12092 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7248 POSTS0 COMMENTS
Thapelo Manthata
6961 POSTS0 COMMENTS
Umr Jansen
6953 POSTS0 COMMENTS