What is the main issue if the directory testdir already exists?
medium
A. mkdir() will fail and echo 'Failed', and rmdir() will fail to remove the directory
B. mkdir() will fail and echo 'Failed', but rmdir() will still remove the directory
C. mkdir() will fail and echo 'Failed', and rmdir() will remove the directory anyway
D. mkdir() will overwrite the existing directory
Solution
Step 1: Behavior of mkdir() when directory exists
If testdir already exists, mkdir() returns false and echoes 'Failed'.
Step 2: Behavior of rmdir() on existing directory
Since the directory exists, rmdir() will attempt to remove it. If the directory is empty and permissions allow, it will succeed. Otherwise, it will fail.
Final Answer:
mkdir() will fail and echo 'Failed', but rmdir() will still remove the directory -> Option B
Quick Check:
mkdir() fails if exists; rmdir() removes empty directory [OK]
5. You want to list all files in a directory docs but skip the special entries . and ... Which PHP code snippet correctly does this?
hard
A. if (is_dir('docs')) {
$dh = opendir('docs');
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
echo $file . ' ';
}
}
closedir($dh);
}
B. if (is_dir('docs')) {
$dh = opendir('docs');
while (($file = readdir($dh))) {
echo $file . ' ';
}
closedir($dh);
}
C. foreach (scandir('docs') as $file) {
echo $file . ' ';
}
D. if (is_dir('docs')) {
$dh = opendir('docs');
while (($file = readdir($dh)) !== false) {
echo $file . ' ';
}
closedir($dh);
}
Solution
Step 1: Understand how to skip '.' and '..'
The special entries '.' and '..' appear in directory listings and must be explicitly skipped.
Step 2: Analyze each code snippet
if (is_dir('docs')) {
$dh = opendir('docs');
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
echo $file . ' ';
}
}
closedir($dh);
} checks if the file is not '.' or '..' before echoing. foreach (scandir('docs') as $file) {
echo $file . ' ';
} uses scandir() but does not skip special entries.
Final Answer:
The snippet using if ($file != '.' && $file != '..') -> Option A
Quick Check:
Skip '.' and '..' with if check inside readdir() loop [OK]
Hint: Use if ($file != '.' && $file != '..') to skip special entries [OK]
Common Mistakes:
Not skipping '.' and '..' entries
Using scandir() without filtering special entries
Forgetting to check for false in readdir() loop
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.