php scandir produces extra elements (2 dots)

拜拜、爱过 提交于 2019-12-11 00:57:47

问题


Hi,

I have the following files in a directory called content: index.php, page1.php, page2.php and page3.php ONLY.

Then I have this code:

 $column = scandir("content");
 foreach ($column as $value) {   
  $stvalue = str_replace(".php", "", $value);    
  echo "<div>$stvalue</div>";
}

Nevertheless, this is what I get:

<div>.</div>
<div>..</div>
<div>index</div>
<div>page1</div>
<div>page2</div>
<div>page3</div>

Whats with the first 2 elements? I dont have files named like that so I dont get it.

Thank you.


回答1:


. - is a special directory referencing the current directory.

.. - is also a special directory and its referencing the parent directory.

To remove the special directories I can think of some options:

1.

foreach(glob("*.php") as $filename) {
    echo "<div>$filename</div>";
}

2.

$files = array_diff(scandir("content"), array('..', '.'));
foreach($files as $file) { ... }

3.

foreach ($files as $file) {    
    if($file != '.' and $file != '..') { ... } 
}

All of the above are alternatives. You don't need to use scandir() if you use glob() and vice versa. glob() - expects a pattern. It is possible to also provide it with the path like this:
glob("[path]/*.php") - this will list any php file located in path. glob() documentation can be found here PHP - glob()




回答2:


$column = scandir("content");
foreach ($column as $value) {   
$stvalue = str_replace(".php", "", $value); 
if($stvalue != '.' || $stvalue != '..')   {
echo "<div>$stvalue</div>";
}
}



回答3:


. refers to the current directory. .. refers to the parent directory. This is why typing cd .. on a command prompt will change to the parent directory. It's been this way in DOS, every version of Windows, Mac OS X, it's not just Linux and UNIX variants.

If you don't want to display them on your page, just skip the first two entries using array_slice.



来源:https://stackoverflow.com/questions/36907031/php-scandir-produces-extra-elements-2-dots

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