0

Can someone please xplain this code. Im reading larry ullmans book on php and i dont get this part. Thanks in advance!!

$search_dir = '.';
$contents = scandir($search_dir);

    print '<h2>Directories</h2>
    <ul>';
    foreach ($contents as $item) {
    if ( (is_dir($search_dir . '/' . $item)) AND (substr($item, 0, 1) != '.') ) {
    print "<li>$item</li>\n";
    }
    }
print '</ul>';

2 Answers 2

1

It shows you list of all directories in current directory

Sign up to request clarification or add additional context in comments.

Comments

0

I'll repost your code with comments to exaplain what each line does.

$search_dir = '.'; //Set the directory to search. "." means the current one.
$contents = scandir($search_dir); //scan the directory and return its results into $contents

print '<h2>Directories</h2>
    <ul>';
foreach($contents as $item) { //Iterate through the array and for each item...
    //If the item is a directory        AND it doesn't start with a . (which means the current one)...
    if ((is_dir($search_dir.'/'.$item)) AND(substr($item, 0, 1) != '.')) {
        print "<li>$item</li>\n"; //Print it
    }
}
print '</ul>';

In short, it prints out an output of the directories inside the directory the script is running in.

5 Comments

thank you! i have one question though. If i take the $search_dir.'/'. away the same result comes up. why is that needed?
That's because if your $search_dir is different then . (you want to get the directories in a different directory), you'd fail, because it'll look for is_dir($item) (on the same directory as the script). By coincidence, the search dir and the current dir are the same.
im sorry to be a pain but how would the array of the $contents look like and how would the $item look like?
From the Manual: "Returns an array of files and directories from the directory." See the examples in that article to understand how the array looks like
thank you! :) i dont understand the dots and why they show up... Array ( [0] => . [1] => .. [2] => bar.php [3] => foo.txt [4] => somedir )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.