php

PHP dynamically populating an array

php

I have an array that lists folders in a directory. Until now, I've been hardcoding the folder names, but rather than do that, I thought I could easily create a script to parse the directory and just assign each folder name to the array. That way, I could easily add folders and not have to touch the script again…

The subject array creates an options list pulldown menu listing each folder…

Currently, the array is hardcoded like so…

"options" => array("folder one" => "folder1", "folder two" => "folder2")),

But I'm trying to make it dynamic based on whatever folders it finds in the given directory.

Here's the script I'm using to parse the directory and return the foldernames to the array. It works fine.

function getDirectory( $path = '.', $level = 0 ){// Directories to ignore when listing output.$ignore = array( '.', '..' );// Open the directory to the handle $dh$dh = @opendir( $path );// Loop through the directorywhile( false !== ( $file = readdir( $dh ) ) )    {    // Check that this file is not to be ignored    if( !in_array( $file, $ignore ) )        {        // Show directories only        if(is_dir( "$path/$file" ) )            {            // Re-call this same function but on a new directory.            // this is what makes function recursive.            //echo $file." => ".$file. ", ";            // need to return the folders in the form expected by the array. Probably could just add the items directly to the array?            $mydir2=$mydir2.'"'.$file.'" => "'.$file. '", ';            getDirectory( "$path/$file", ($level+1) );        }    }}return $mydir2;// Close the directory handleclosedir( $dh );}

And here's my first take at getting those folders into the array…

$mydir = getDirectory('/images/');"options" => array($mydir)),

But obviously, that doesn't work correctly since its not feeding the array properly I just get a string in my options list… I'm sure this is an easy conversion step I'm missing…

Best Solution

You want to create an array, not a string.

// Replace$mydir2=$mydir2.'"'.$file.'" => "'.$file. '", ';// With$mydir2[$file] = $file;

Also, close $dh before returning. Now, closedir is never called.