Why is it whenever I use scandir() I receive periods at the beginning of the array?

為{幸葍}努か 提交于 2019-12-17 09:46:53

问题


Why is it whenever I use scandir() I receive periods at the beginning of the array?

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

回答1:


Those are the current (.) and parent (..) directories. They are present in all directories, and are used to refer to the directory itself and its direct parent.




回答2:


There are two entries present in every directory listing:

  • . refers to the current directory
  • .. refers to the parent directory (or the root, if the current directory is the root)

You can remove them from the results by filtering them out of the results of scandir:

$allFiles = scandir(__DIR__); // Or any other directory
$files = array_diff($allFiles, array('.', '..'));



回答3:


To remove . and .. from scandir use this function:

function scandir1($dir)
{
    return array_values(array_diff(scandir($dir), array('..', '.')));
}

The array_values command re-indexes the array so that it starts from 0. If you don't need the array re-indexing, then the accepted answer will work fine. Simply: array_diff(scandir($dir), array('..', '.')).




回答4:


In Unix convention . is a link to the current directory while .. is a link to the parent directory. Both of them exist as a file in the directory index.




回答5:


In one line of code:

$files=array_slice(scandir('/path/to/directory/'), 2);


来源:https://stackoverflow.com/questions/7132399/why-is-it-whenever-i-use-scandir-i-receive-periods-at-the-beginning-of-the-arr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!