Friday, October 10, 2025
HomeLanguagesPHP | DirectoryIterator rewind() Function

PHP | DirectoryIterator rewind() Function

The DirectoryIterator::rewind() function is an inbuilt function in PHP which is used to rewind the DirectoryIterator back to the start position.

Syntax:

void DirectoryIterator::rewind( void )

Parameters: This function does not accept any parameters.

Return Value: This function does not return any value.

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

Program 1:




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


Output:

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

Program 2:




<?php
  
// Create a directory Iterator
$directory = new DirectoryIterator(dirname(__FILE__));
  
// Loop runs for each element of directory
foreach($directory as $dir) {
  
    // Display key and file name
    echo $dir->key() . " => "
    $dir->getFilename() . "<br>";
}
  
// Use rewind() function to move to
// the start position
$directory->rewind();
  
// Display key and file name
echo $directory->key() . " => "
        $directory->getFilename();
  
?>


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
0 => .

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

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

RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6718 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS