topic: file-io (read / write / CSV / paths / upload概念) / ch05 — パス操作とディレクトリ走査 / 演習 02
📝 ドリル 02 — `scandir` でディレクトリ一覧
問題
__DIR__ . '/tests/data/sample' 配下のファイル名を、. と .. を除いた 上で 昇順 にソートして 1 行ずつ出力してください。
tests/data/sample/ の中身 (このリポジトリにコミット済み):
apple.txt
banana.txt
cherry.txt
期待される出力:
apple.txt
banana.txt
cherry.txt
採点
php scripts/grade.php topics/14-file-io/ch05-paths/drill/02-list-dir/
ヒント
$dir = __DIR__ . '/tests/data/sample';
$files = array_values(array_diff(scandir($dir), ['.', '..']));
sort($files);
foreach ($files as $f) {
echo $f . "\n";
}scandir($dir)はディレクトリ内のエントリ名を配列で返す- 戻り値には 必ず
.(カレント)・..(親) が含まれる のでarray_diffで除く array_valuesで キーを 0 から振り直す (array_diffは元のキーを保つため、後段のsort不要な順序ズレを防ぐ)sort($files)で 明示的に昇順 (PHP / OS 環境差を消す)
つまづいたら
- 出力の先頭に
...が混ざる →array_diff(scandir($dir), ['.', '..'])でカレント・親エントリを除く - 順序がバラバラ
→
sort($files)を明示的に呼ぶ。scandirのデフォルトは昇順だが、OS / ファイルシステム差で揺れることもある - 出力が 1 行に詰まる
→
echoの末尾に"\n"を付けるのを忘れている
テストケース
期待される出力
apple.txt
banana.txt
cherry.txt
📄 starter.php(雛形)
このコードから書き始めてください。
<?php
// TODO: tests/data/sample のディレクトリパスを __DIR__ ベースで作る
// $dir = __DIR__ . '/...';
// TODO: scandir($dir) でファイル名一覧を取り、array_diff で '.' と '..' を除く
// $files = array_values(array_diff(scandir($dir), ['.', '..']));
// TODO: sort($files) で昇順に並べる (環境依存を消すために明示)
// TODO: foreach で 1 行ずつ出力する (末尾に "\n")
✅ 解答例を見る(自分で解いてから)
<?php
// tests/data/sample/ 配下のファイル名一覧を、. / .. を除いて昇順で出力する
$dir = __DIR__ . '/tests/data/sample';
$files = array_values(array_diff(scandir($dir), ['.', '..']));
sort($files);
foreach ($files as $f) {
echo $f . "\n";
}