PHP readdir Function: Reading Directory Entries
Provides a detailed explanation of PHP's readdir function, including its signature, parameters, return values, and example code demonstrating correct and incorrect ways to iterate through directory entries using a directory handle opened by opendir().
Function signature: string readdir(resource $dir_handle)
Returns the next filename from the directory handle opened by opendir() . Filenames are returned in the order they appear in the filesystem. On failure, the function returns FALSE .
Parameter
$dir_handle – a directory handle resource previously obtained via opendir() .
Return value
On success, the filename string.
On failure, FALSE .
Example (correct usage)
<?php
// Note: before 4.0.0-RC2 the !== operator does not exist
$handle = opendir('/path/to/files');
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to iterate a directory */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
closedir($handle);
?>Example (incorrect usage)
<?php
while ($file = readdir($handle)) {
echo "$file\n";
}
closedir($handle);
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.