LoginSignup
0
0

More than 3 years have passed since last update.

scandir での . ..を排除する方法

Posted at

phpのscandir関数をつかうと、"." ".."が付く

通常Linuxコマンドの ls -la と同じようにscandirでは、"." ".."が付く。

これを取り除く方法には以下の方法がある。

昔のPHP Docのサンプルコードでトップに来てた記法

<?php
$files = array_slice(scandir('/path/to/directory/'), 2);
.      <- 上2つが取り除かれる
..     <- 上2つが取り除かれる
files
folder

Search Codeで調べてみると意外と残ってる。

この記法の問題点は必ず "." ".." が一番上に来る事が念願に置かれているのだが、以下の文字列が先端にある場合には来ない。

( -

(test)test.txt
-test.txt
.
..
files
folder

特に日本の場合は、(最終決定版)プレゼンテーション資料.pptxのような名付けをすることもあるので、英数字意外の文字列を使用する事が分かっている場合は別の記法が必要となる。

現在の最適解

<?php
$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));

PHPのDocのサンプルコードはあくまでもユーザの投稿で、トップの記法でも最適解ではない可能性もあることを念頭に置いておきたい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0