readdir

(PHP 4, PHP 5, PHP 7, PHP 8)

readdirRead entry from directory handle

Опис

readdir(?resource $dir_handle = null): string|false

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

Параметри

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Значення, що повертаються

Returns the entry name on success або false в разі помилки.

Увага

Ця функція може повертати як логічне false, так і не логічне значення, яке прирівнюється до false. Докладніше про це описано в розділі Логічні типи даних. Для перевірки значення, яке повертає ця функція, використовується оператор ===.

Журнал змін

Версія Опис
8.0.0 dir_handle is now nullable.

Приклади

Приклад #1 List all entries in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) false since otherwise, any directory entry whose name evaluates to false will stop the loop (e.g. a directory named "0").

<?php

if ($handle = opendir('/path/to/files')) {
echo
"Directory handle: $handle\n";
echo
"Entries:\n";

/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo
"$entry\n";
}

/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo
"$entry\n";
}

closedir($handle);
}
?>

Приклад #2 List all entries in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
while (
false !== ($entry = readdir($handle))) {
if (
$entry != "." && $entry != "..") {
echo
"$entry\n";
}
}
closedir($handle);
}
?>

Прогляньте також

  • is_dir() - Tells whether the filename is a directory
  • glob() - Find pathnames matching a pattern
  • opendir() - Open directory handle
  • scandir() - List files and directories inside the specified path