Challenge - 5 Problems
Directory Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code listing directory contents?
Consider this PHP code that reads and prints the names of files in a directory.
PHP
<?php $dir = 'testdir'; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { echo "$file\n"; } closedir($dh); } } ?>
Attempts:
2 left
💡 Hint
Remember readdir returns '.' and '..' entries by default.
✗ Incorrect
The code opens the directory and reads all entries including '.' and '..'. It prints each entry on a new line.
❓ Predict Output
intermediate2:00remaining
What does this PHP code output when filtering directory files?
This PHP code lists only files (not directories) inside 'myfolder'. What is the output?
PHP
<?php $dir = 'myfolder'; $files = []; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if ($file !== '.' && $file !== '..' && is_file($dir . DIRECTORY_SEPARATOR . $file)) { $files[] = $file; } } closedir($dh); } } echo count($files); ?>
Attempts:
2 left
💡 Hint
is_file checks if the path is a regular file, not a directory.
✗ Incorrect
The code counts only files, skipping '.' and '..' and directories, so it prints the number of files inside 'myfolder'.
❓ Predict Output
advanced2:00remaining
What error does this PHP code raise when trying to remove a directory?
This code tries to remove a directory named 'oldfolder'. What error or output occurs?
PHP
<?php $dir = 'oldfolder'; rmdir($dir); echo "Removed"; ?>
Attempts:
2 left
💡 Hint
rmdir only removes empty directories.
✗ Incorrect
rmdir fails with a warning if the directory is not empty. It does not remove directories with files inside.
❓ Predict Output
advanced2:00remaining
What is the output of this PHP code creating a directory?
This PHP code tries to create a directory 'newdir' with permissions 0755. What is the output?
PHP
<?php $dir = 'newdir'; if (mkdir($dir, 0755)) { echo "Created"; } else { echo "Failed"; } ?>
Attempts:
2 left
💡 Hint
mkdir returns true on success, false on failure.
✗ Incorrect
mkdir creates the directory if it does not exist and returns true, so 'Created' is printed.
🧠 Conceptual
expert2:00remaining
How many items are in the array after this PHP directory scan?
This PHP code scans a directory and filters out '.' and '..'. How many items does the array contain?
PHP
<?php $dir = 'sampledir'; $items = scandir($dir); $filtered = array_filter($items, fn($item) => $item !== '.' && $item !== '..'); echo count($filtered); ?>
Attempts:
2 left
💡 Hint
scandir returns all entries including '.' and '..'.
✗ Incorrect
scandir returns all entries. The filter removes '.' and '..', so count is all files and directories except those two.